test_transforms_v2.py 19.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
import itertools
import random

import numpy as np

import PIL.Image
import pytest
import torch
import torchvision.transforms.v2 as transforms

11
from common_utils import assert_equal, cpu_and_cuda
12
from torchvision import tv_tensors
13
14
from torchvision.ops.boxes import box_iou
from torchvision.transforms.functional import to_pil_image
15
16
from torchvision.transforms.v2._utils import is_pure_tensor
from transforms_v2_legacy_utils import make_bounding_boxes, make_detection_mask, make_image, make_images, make_videos
17
18
19
20
21
22
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


def make_vanilla_tensor_images(*args, **kwargs):
    for image in make_images(*args, **kwargs):
        if image.ndim > 3:
            continue
        yield image.data


def make_pil_images(*args, **kwargs):
    for image in make_vanilla_tensor_images(*args, **kwargs):
        yield to_pil_image(image)


def parametrize(transforms_with_inputs):
    return pytest.mark.parametrize(
        ("transform", "input"),
        [
            pytest.param(
                transform,
                input,
                id=f"{type(transform).__name__}-{type(input).__module__}.{type(input).__name__}-{idx}",
            )
            for transform, inputs in transforms_with_inputs
            for idx, input in enumerate(inputs)
        ],
    )


@pytest.mark.parametrize(
    "flat_inputs",
    itertools.permutations(
        [
            next(make_vanilla_tensor_images()),
            next(make_vanilla_tensor_images()),
            next(make_pil_images()),
            make_image(),
            next(make_videos()),
        ],
        3,
    ),
)
59
60
def test_pure_tensor_heuristic(flat_inputs):
    def split_on_pure_tensor(to_split):
61
        # This takes a sequence that is structurally aligned with `flat_inputs` and splits its items into three parts:
62
63
        # 1. The first pure tensor. If none is present, this will be `None`
        # 2. A list of the remaining pure tensors
64
        # 3. A list of all other items
65
        pure_tensors = []
66
67
68
69
        others = []
        # Splitting always happens on the original `flat_inputs` to avoid any erroneous type changes by the transform to
        # affect the splitting.
        for item, inpt in zip(to_split, flat_inputs):
70
71
            (pure_tensors if is_pure_tensor(inpt) else others).append(item)
        return pure_tensors[0] if pure_tensors else None, pure_tensors[1:], others
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

    class CopyCloneTransform(transforms.Transform):
        def _transform(self, inpt, params):
            return inpt.clone() if isinstance(inpt, torch.Tensor) else inpt.copy()

        @staticmethod
        def was_applied(output, inpt):
            identity = output is inpt
            if identity:
                return False

            # Make sure nothing fishy is going on
            assert_equal(output, inpt)
            return True

87
    first_pure_tensor_input, other_pure_tensor_inputs, other_inputs = split_on_pure_tensor(flat_inputs)
88
89
90
91

    transform = CopyCloneTransform()
    transformed_sample = transform(flat_inputs)

92
    first_pure_tensor_output, other_pure_tensor_outputs, other_outputs = split_on_pure_tensor(transformed_sample)
93

94
    if first_pure_tensor_input is not None:
95
        if other_inputs:
96
            assert not transform.was_applied(first_pure_tensor_output, first_pure_tensor_input)
97
        else:
98
            assert transform.was_applied(first_pure_tensor_output, first_pure_tensor_input)
99

100
    for output, inpt in zip(other_pure_tensor_outputs, other_pure_tensor_inputs):
101
102
103
104
105
106
107
108
109
        assert not transform.was_applied(output, inpt)

    for input, output in zip(other_inputs, other_outputs):
        assert transform.was_applied(output, input)


class TestTransform:
    @pytest.mark.parametrize(
        "inpt_type",
110
        [torch.Tensor, PIL.Image.Image, tv_tensors.Image, np.ndarray, tv_tensors.BoundingBoxes, str, int],
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
    )
    def test_check_transformed_types(self, inpt_type, mocker):
        # This test ensures that we correctly handle which types to transform and which to bypass
        t = transforms.Transform()
        inpt = mocker.MagicMock(spec=inpt_type)

        if inpt_type in (np.ndarray, str, int):
            output = t(inpt)
            assert output is inpt
        else:
            with pytest.raises(NotImplementedError):
                t(inpt)


class TestRandomIoUCrop:
126
    @pytest.mark.parametrize("device", cpu_and_cuda())
127
    @pytest.mark.parametrize("options", [[0.5, 0.9], [2.0]])
Philip Meier's avatar
Philip Meier committed
128
129
130
    def test__get_params(self, device, options):
        orig_h, orig_w = size = (24, 32)
        image = make_image(size)
131
        bboxes = tv_tensors.BoundingBoxes(
132
133
            torch.tensor([[1, 1, 10, 10], [20, 20, 23, 23], [1, 20, 10, 23], [20, 1, 23, 10]]),
            format="XYXY",
Philip Meier's avatar
Philip Meier committed
134
            canvas_size=size,
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
            device=device,
        )
        sample = [image, bboxes]

        transform = transforms.RandomIoUCrop(sampler_options=options)

        n_samples = 5
        for _ in range(n_samples):

            params = transform._get_params(sample)

            if options == [2.0]:
                assert len(params) == 0
                return

            assert len(params["is_within_crop_area"]) > 0
            assert params["is_within_crop_area"].dtype == torch.bool

            assert int(transform.min_scale * orig_h) <= params["height"] <= int(transform.max_scale * orig_h)
            assert int(transform.min_scale * orig_w) <= params["width"] <= int(transform.max_scale * orig_w)

            left, top = params["left"], params["top"]
            new_h, new_w = params["height"], params["width"]
            ious = box_iou(
                bboxes,
                torch.tensor([[left, top, left + new_w, top + new_h]], dtype=bboxes.dtype, device=bboxes.device),
            )
            assert ious.max() >= options[0] or ious.max() >= options[1], f"{ious} vs {options}"

    def test__transform_empty_params(self, mocker):
        transform = transforms.RandomIoUCrop(sampler_options=[2.0])
166
167
        image = tv_tensors.Image(torch.rand(1, 3, 4, 4))
        bboxes = tv_tensors.BoundingBoxes(torch.tensor([[1, 1, 2, 2]]), format="XYXY", canvas_size=(4, 4))
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
        label = torch.tensor([1])
        sample = [image, bboxes, label]
        # Let's mock transform._get_params to control the output:
        transform._get_params = mocker.MagicMock(return_value={})
        output = transform(sample)
        torch.testing.assert_close(output, sample)

    def test_forward_assertion(self):
        transform = transforms.RandomIoUCrop()
        with pytest.raises(
            TypeError,
            match="requires input sample to contain tensor or PIL images and bounding boxes",
        ):
            transform(torch.tensor(0))

    def test__transform(self, mocker):
        transform = transforms.RandomIoUCrop()

Philip Meier's avatar
Philip Meier committed
186
187
        size = (32, 24)
        image = make_image(size)
188
        bboxes = make_bounding_boxes(format="XYXY", canvas_size=size, batch_dims=(6,))
Philip Meier's avatar
Philip Meier committed
189
        masks = make_detection_mask(size, num_objects=6)
190
191
192
193
194
195
196
197
198
199
200

        sample = [image, bboxes, masks]

        is_within_crop_area = torch.tensor([0, 1, 0, 1, 0, 1], dtype=torch.bool)

        params = dict(top=1, left=2, height=12, width=12, is_within_crop_area=is_within_crop_area)
        transform._get_params = mocker.MagicMock(return_value=params)
        output = transform(sample)

        # check number of bboxes vs number of labels:
        output_bboxes = output[1]
201
        assert isinstance(output_bboxes, tv_tensors.BoundingBoxes)
202
203
204
        assert (output_bboxes[~is_within_crop_area] == 0).all()

        output_masks = output[2]
205
        assert isinstance(output_masks, tv_tensors.Mask)
206
207
208
209


class TestRandomShortestSize:
    @pytest.mark.parametrize("min_size,max_size", [([5, 9], 20), ([5, 9], None)])
Philip Meier's avatar
Philip Meier committed
210
211
    def test__get_params(self, min_size, max_size):
        canvas_size = (3, 10)
212

213
        transform = transforms.RandomShortestSize(min_size=min_size, max_size=max_size, antialias=True)
214

Philip Meier's avatar
Philip Meier committed
215
        sample = make_image(canvas_size)
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
        params = transform._get_params([sample])

        assert "size" in params
        size = params["size"]

        assert isinstance(size, tuple) and len(size) == 2

        longer = max(size)
        shorter = min(size)
        if max_size is not None:
            assert longer <= max_size
            assert shorter <= max_size
        else:
            assert shorter in min_size


class TestRandomResize:
    def test__get_params(self):
        min_size = 3
        max_size = 6

237
        transform = transforms.RandomResize(min_size=min_size, max_size=max_size, antialias=True)
238
239
240
241
242
243
244
245
246
247

        for _ in range(10):
            params = transform._get_params([])

            assert isinstance(params["size"], list) and len(params["size"]) == 1
            size = params["size"][0]

            assert min_size <= size < max_size


248
@pytest.mark.parametrize("image_type", (PIL.Image, torch.Tensor, tv_tensors.Image))
249
250
@pytest.mark.parametrize("label_type", (torch.Tensor, int))
@pytest.mark.parametrize("dataset_return_type", (dict, tuple))
251
@pytest.mark.parametrize("to_tensor", (transforms.ToTensor, transforms.ToImage))
252
253
def test_classif_preset(image_type, label_type, dataset_return_type, to_tensor):

254
    image = tv_tensors.Image(torch.randint(0, 256, size=(1, 3, 250, 250), dtype=torch.uint8))
255
256
257
258
    if image_type is PIL.Image:
        image = to_pil_image(image[0])
    elif image_type is torch.Tensor:
        image = image.as_subclass(torch.Tensor)
259
        assert is_pure_tensor(image)
260
261
262
263
264
265
266
267
268
269
270

    label = 1 if label_type is int else torch.tensor([1])

    if dataset_return_type is dict:
        sample = {
            "image": image,
            "label": label,
        }
    else:
        sample = image, label

271
272
273
274
275
276
    if to_tensor is transforms.ToTensor:
        with pytest.warns(UserWarning, match="deprecated and will be removed"):
            to_tensor = to_tensor()
    else:
        to_tensor = to_tensor()

277
278
    t = transforms.Compose(
        [
279
            transforms.RandomResizedCrop((224, 224), antialias=True),
280
281
282
283
284
            transforms.RandomHorizontalFlip(p=1),
            transforms.RandAugment(),
            transforms.TrivialAugmentWide(),
            transforms.AugMix(),
            transforms.AutoAugment(),
285
            to_tensor,
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
            # TODO: ConvertImageDtype is a pass-through on PIL images, is that
            # intended?  This results in a failure if we convert to tensor after
            # it, because the image would still be uint8 which make Normalize
            # fail.
            transforms.ConvertImageDtype(torch.float),
            transforms.Normalize(mean=[0, 0, 0], std=[1, 1, 1]),
            transforms.RandomErasing(p=1),
        ]
    )

    out = t(sample)

    assert type(out) == type(sample)

    if dataset_return_type is tuple:
        out_image, out_label = out
    else:
        assert out.keys() == sample.keys()
        out_image, out_label = out.values()

    assert out_image.shape[-2:] == (224, 224)
    assert out_label == label


310
@pytest.mark.parametrize("image_type", (PIL.Image, torch.Tensor, tv_tensors.Image))
311
@pytest.mark.parametrize("data_augmentation", ("hflip", "lsj", "multiscale", "ssd", "ssdlite"))
312
@pytest.mark.parametrize("to_tensor", (transforms.ToTensor, transforms.ToImage))
313
314
315
@pytest.mark.parametrize("sanitize", (True, False))
def test_detection_preset(image_type, data_augmentation, to_tensor, sanitize):
    torch.manual_seed(0)
316
317
318
319
320
321
322

    if to_tensor is transforms.ToTensor:
        with pytest.warns(UserWarning, match="deprecated and will be removed"):
            to_tensor = to_tensor()
    else:
        to_tensor = to_tensor()

323
324
325
    if data_augmentation == "hflip":
        t = [
            transforms.RandomHorizontalFlip(p=1),
326
            to_tensor,
327
328
329
330
331
332
333
334
335
            transforms.ConvertImageDtype(torch.float),
        ]
    elif data_augmentation == "lsj":
        t = [
            transforms.ScaleJitter(target_size=(1024, 1024), antialias=True),
            # Note: replaced FixedSizeCrop with RandomCrop, becuase we're
            # leaving FixedSizeCrop in prototype for now, and it expects Label
            # classes which we won't release yet.
            # transforms.FixedSizeCrop(
336
            #     size=(1024, 1024), fill=defaultdict(lambda: (123.0, 117.0, 104.0), {tv_tensors.Mask: 0})
337
338
339
            # ),
            transforms.RandomCrop((1024, 1024), pad_if_needed=True),
            transforms.RandomHorizontalFlip(p=1),
340
            to_tensor,
341
342
343
344
345
346
347
348
            transforms.ConvertImageDtype(torch.float),
        ]
    elif data_augmentation == "multiscale":
        t = [
            transforms.RandomShortestSize(
                min_size=(480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800), max_size=1333, antialias=True
            ),
            transforms.RandomHorizontalFlip(p=1),
349
            to_tensor,
350
351
352
353
354
            transforms.ConvertImageDtype(torch.float),
        ]
    elif data_augmentation == "ssd":
        t = [
            transforms.RandomPhotometricDistort(p=1),
355
            transforms.RandomZoomOut(fill={"others": (123.0, 117.0, 104.0), tv_tensors.Mask: 0}, p=1),
356
357
            transforms.RandomIoUCrop(),
            transforms.RandomHorizontalFlip(p=1),
358
            to_tensor,
359
360
361
362
363
364
            transforms.ConvertImageDtype(torch.float),
        ]
    elif data_augmentation == "ssdlite":
        t = [
            transforms.RandomIoUCrop(),
            transforms.RandomHorizontalFlip(p=1),
365
            to_tensor,
366
367
368
            transforms.ConvertImageDtype(torch.float),
        ]
    if sanitize:
369
        t += [transforms.SanitizeBoundingBoxes()]
370
371
372
373
374
    t = transforms.Compose(t)

    num_boxes = 5
    H = W = 250

375
    image = tv_tensors.Image(torch.randint(0, 256, size=(1, 3, H, W), dtype=torch.uint8))
376
377
378
379
    if image_type is PIL.Image:
        image = to_pil_image(image[0])
    elif image_type is torch.Tensor:
        image = image.as_subclass(torch.Tensor)
380
        assert is_pure_tensor(image)
381
382
383
384
385
386

    label = torch.randint(0, 10, size=(num_boxes,))

    boxes = torch.randint(0, min(H, W) // 2, size=(num_boxes, 4))
    boxes[:, 2:] += boxes[:, :2]
    boxes = boxes.clamp(min=0, max=min(H, W))
387
    boxes = tv_tensors.BoundingBoxes(boxes, format="XYXY", canvas_size=(H, W))
388

389
    masks = tv_tensors.Mask(torch.randint(0, 2, size=(num_boxes, H, W), dtype=torch.uint8))
390
391
392
393
394
395
396
397
398
399

    sample = {
        "image": image,
        "label": label,
        "boxes": boxes,
        "masks": masks,
    }

    out = t(sample)

400
    if isinstance(to_tensor, transforms.ToTensor) and image_type is not tv_tensors.Image:
401
        assert is_pure_tensor(out["image"])
402
    else:
403
        assert isinstance(out["image"], tv_tensors.Image)
404
405
406
407
408
409
    assert isinstance(out["label"], type(sample["label"]))

    num_boxes_expected = {
        # ssd and ssdlite contain RandomIoUCrop which may "remove" some bbox. It
        # doesn't remove them strictly speaking, it just marks some boxes as
        # degenerate and those boxes will be later removed by
410
        # SanitizeBoundingBoxes(), which we add to the pipelines if the sanitize
411
412
413
        # param is True.
        # Note that the values below are probably specific to the random seed
        # set above (which is fine).
414
        (True, "ssd"): 5,
415
416
417
418
419
420
421
        (True, "ssdlite"): 4,
    }.get((sanitize, data_augmentation), num_boxes)

    assert out["boxes"].shape[0] == out["masks"].shape[0] == out["label"].shape[0] == num_boxes_expected


@pytest.mark.parametrize("min_size", (1, 10))
422
@pytest.mark.parametrize("labels_getter", ("default", lambda inputs: inputs["labels"], None, lambda inputs: None))
423
424
425
426
427
428
429
430
@pytest.mark.parametrize("sample_type", (tuple, dict))
def test_sanitize_bounding_boxes(min_size, labels_getter, sample_type):

    if sample_type is tuple and not isinstance(labels_getter, str):
        # The "lambda inputs: inputs["labels"]" labels_getter used in this test
        # doesn't work if the input is a tuple.
        return

431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
    H, W = 256, 128

    boxes_and_validity = [
        ([0, 1, 10, 1], False),  # Y1 == Y2
        ([0, 1, 0, 20], False),  # X1 == X2
        ([0, 0, min_size - 1, 10], False),  # H < min_size
        ([0, 0, 10, min_size - 1], False),  # W < min_size
        ([0, 0, 10, H + 1], False),  # Y2 > H
        ([0, 0, W + 1, 10], False),  # X2 > W
        ([-1, 1, 10, 20], False),  # any < 0
        ([0, 0, -1, 20], False),  # any < 0
        ([0, 0, -10, -1], False),  # any < 0
        ([0, 0, min_size, 10], True),  # H < min_size
        ([0, 0, 10, min_size], True),  # W < min_size
        ([0, 0, W, H], True),  # TODO: Is that actually OK?? Should it be -1?
        ([1, 1, 30, 20], True),
        ([0, 0, 10, 10], True),
        ([1, 1, 30, 20], True),
    ]

    random.shuffle(boxes_and_validity)  # For test robustness: mix order of wrong and correct cases
    boxes, is_valid_mask = zip(*boxes_and_validity)
    valid_indices = [i for (i, is_valid) in enumerate(is_valid_mask) if is_valid]

    boxes = torch.tensor(boxes)
    labels = torch.arange(boxes.shape[0])

458
    boxes = tv_tensors.BoundingBoxes(
459
        boxes,
460
        format=tv_tensors.BoundingBoxFormat.XYXY,
Philip Meier's avatar
Philip Meier committed
461
        canvas_size=(H, W),
462
463
    )

464
    masks = tv_tensors.Mask(torch.randint(0, 2, size=(boxes.shape[0], H, W)))
465
466
    whatever = torch.rand(10)
    input_img = torch.randint(0, 256, size=(1, 3, H, W), dtype=torch.uint8)
467
    sample = {
468
        "image": input_img,
469
470
        "labels": labels,
        "boxes": boxes,
471
        "whatever": whatever,
472
473
474
475
        "None": None,
        "masks": masks,
    }

476
477
478
479
    if sample_type is tuple:
        img = sample.pop("image")
        sample = (img, sample)

480
    out = transforms.SanitizeBoundingBoxes(min_size=min_size, labels_getter=labels_getter)(sample)
481

482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
    if sample_type is tuple:
        out_image = out[0]
        out_labels = out[1]["labels"]
        out_boxes = out[1]["boxes"]
        out_masks = out[1]["masks"]
        out_whatever = out[1]["whatever"]
    else:
        out_image = out["image"]
        out_labels = out["labels"]
        out_boxes = out["boxes"]
        out_masks = out["masks"]
        out_whatever = out["whatever"]

    assert out_image is input_img
    assert out_whatever is whatever
497

498
499
    assert isinstance(out_boxes, tv_tensors.BoundingBoxes)
    assert isinstance(out_masks, tv_tensors.Mask)
500

501
    if labels_getter is None or (callable(labels_getter) and labels_getter({"labels": "blah"}) is None):
502
        assert out_labels is labels
503
    else:
504
505
        assert isinstance(out_labels, torch.Tensor)
        assert out_boxes.shape[0] == out_labels.shape[0] == out_masks.shape[0]
506
        # This works because we conveniently set labels to arange(num_boxes)
507
        assert out_labels.tolist() == valid_indices
508
509


510
511
512
513
514
515
516
517
518
519
def test_sanitize_bounding_boxes_no_label():
    # Non-regression test for https://github.com/pytorch/vision/issues/7878

    img = make_image()
    boxes = make_bounding_boxes()

    with pytest.raises(ValueError, match="or a two-tuple whose second item is a dict"):
        transforms.SanitizeBoundingBoxes()(img, boxes)

    out_img, out_boxes = transforms.SanitizeBoundingBoxes(labels_getter=None)(img, boxes)
520
521
    assert isinstance(out_img, tv_tensors.Image)
    assert isinstance(out_boxes, tv_tensors.BoundingBoxes)
522
523


524
525
def test_sanitize_bounding_boxes_errors():

526
    good_bbox = tv_tensors.BoundingBoxes(
527
        [[0, 0, 10, 10]],
528
        format=tv_tensors.BoundingBoxFormat.XYXY,
Philip Meier's avatar
Philip Meier committed
529
        canvas_size=(20, 20),
530
531
532
    )

    with pytest.raises(ValueError, match="min_size must be >= 1"):
533
        transforms.SanitizeBoundingBoxes(min_size=0)
534
    with pytest.raises(ValueError, match="labels_getter should either be 'default'"):
535
        transforms.SanitizeBoundingBoxes(labels_getter=12)
536
537
538

    with pytest.raises(ValueError, match="Could not infer where the labels are"):
        bad_labels_key = {"bbox": good_bbox, "BAD_KEY": torch.arange(good_bbox.shape[0])}
539
        transforms.SanitizeBoundingBoxes()(bad_labels_key)
540
541
542

    with pytest.raises(ValueError, match="must be a tensor"):
        not_a_tensor = {"bbox": good_bbox, "labels": torch.arange(good_bbox.shape[0]).tolist()}
543
        transforms.SanitizeBoundingBoxes()(not_a_tensor)
544
545
546

    with pytest.raises(ValueError, match="Number of boxes"):
        different_sizes = {"bbox": good_bbox, "labels": torch.arange(good_bbox.shape[0] + 3)}
547
        transforms.SanitizeBoundingBoxes()(different_sizes)