presets.py 3.56 KB
Newer Older
1
import torch
2
from torchvision.transforms.functional import InterpolationMode
3
4


5
6
7
8
9
10
11
12
13
14
15
16
def get_module(use_v2):
    # We need a protected import to avoid the V2 warning in case just V1 is used
    if use_v2:
        import torchvision.transforms.v2

        return torchvision.transforms.v2
    else:
        import torchvision.transforms

        return torchvision.transforms


17
class ClassificationPresetTrain:
18
19
20
    # Note: this transform assumes that the input to forward() are always PIL
    # images, regardless of the backend parameter. We may change that in the
    # future though, if we change the output type from the dataset.
21
22
    def __init__(
        self,
23
        *,
24
25
26
        crop_size,
        mean=(0.485, 0.456, 0.406),
        std=(0.229, 0.224, 0.225),
27
        interpolation=InterpolationMode.BILINEAR,
28
29
        hflip_prob=0.5,
        auto_augment_policy=None,
Ponku's avatar
Ponku committed
30
31
        ra_magnitude=9,
        augmix_severity=3,
32
        random_erase_prob=0.0,
33
        backend="pil",
34
        use_v2=False,
35
    ):
36
        T = get_module(use_v2)
37
38

        transforms = []
39
40
        backend = backend.lower()
        if backend == "tensor":
41
            transforms.append(T.PILToTensor())
42
43
44
        elif backend != "pil":
            raise ValueError(f"backend can be 'tensor' or 'pil', but got {backend}")

45
        transforms.append(T.RandomResizedCrop(crop_size, interpolation=interpolation, antialias=True))
46
        if hflip_prob > 0:
47
            transforms.append(T.RandomHorizontalFlip(hflip_prob))
48
        if auto_augment_policy is not None:
49
            if auto_augment_policy == "ra":
50
                transforms.append(T.RandAugment(interpolation=interpolation, magnitude=ra_magnitude))
51
            elif auto_augment_policy == "ta_wide":
52
                transforms.append(T.TrivialAugmentWide(interpolation=interpolation))
53
            elif auto_augment_policy == "augmix":
54
                transforms.append(T.AugMix(interpolation=interpolation, severity=augmix_severity))
55
            else:
56
57
                aa_policy = T.AutoAugmentPolicy(auto_augment_policy)
                transforms.append(T.AutoAugment(policy=aa_policy, interpolation=interpolation))
58
59

        if backend == "pil":
60
            transforms.append(T.PILToTensor())
61

62
        transforms.extend(
63
            [
64
65
                T.ConvertImageDtype(torch.float),
                T.Normalize(mean=mean, std=std),
66
67
            ]
        )
68
        if random_erase_prob > 0:
69
            transforms.append(T.RandomErasing(p=random_erase_prob))
70

71
        self.transforms = T.Compose(transforms)
72
73
74
75
76
77

    def __call__(self, img):
        return self.transforms(img)


class ClassificationPresetEval:
78
79
    def __init__(
        self,
80
        *,
81
82
83
84
85
        crop_size,
        resize_size=256,
        mean=(0.485, 0.456, 0.406),
        std=(0.229, 0.224, 0.225),
        interpolation=InterpolationMode.BILINEAR,
86
        backend="pil",
87
        use_v2=False,
88
    ):
89
        T = get_module(use_v2)
90
        transforms = []
91
92
        backend = backend.lower()
        if backend == "tensor":
93
            transforms.append(T.PILToTensor())
94
        elif backend != "pil":
95
96
            raise ValueError(f"backend can be 'tensor' or 'pil', but got {backend}")

97
        transforms += [
98
99
            T.Resize(resize_size, interpolation=interpolation, antialias=True),
            T.CenterCrop(crop_size),
100
101
102
        ]

        if backend == "pil":
103
            transforms.append(T.PILToTensor())
104

105
        transforms += [
106
107
            T.ConvertImageDtype(torch.float),
            T.Normalize(mean=mean, std=std),
108
109
        ]

110
        self.transforms = T.Compose(transforms)
111
112
113

    def __call__(self, img):
        return self.transforms(img)