presets.py 1.75 KB
Newer Older
1
from torchvision.transforms import autoaugment, transforms
2
from torchvision.transforms.functional import InterpolationMode
3
4
5
6
7
8
9
10
11


class ClassificationPresetTrain:
    def __init__(self, crop_size, mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225), hflip_prob=0.5,
                 auto_augment_policy=None, random_erase_prob=0.0):
        trans = [transforms.RandomResizedCrop(crop_size)]
        if hflip_prob > 0:
            trans.append(transforms.RandomHorizontalFlip(hflip_prob))
        if auto_augment_policy is not None:
12
13
            if auto_augment_policy == "ra":
                trans.append(autoaugment.RandAugment())
14
15
            elif auto_augment_policy == "ta_wide":
                trans.append(autoaugment.TrivialAugmentWide())
16
17
18
            else:
                aa_policy = autoaugment.AutoAugmentPolicy(auto_augment_policy)
                trans.append(autoaugment.AutoAugment(policy=aa_policy))
19
20
21
22
23
24
25
26
27
28
29
30
31
32
        trans.extend([
            transforms.ToTensor(),
            transforms.Normalize(mean=mean, std=std),
        ])
        if random_erase_prob > 0:
            trans.append(transforms.RandomErasing(p=random_erase_prob))

        self.transforms = transforms.Compose(trans)

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


class ClassificationPresetEval:
33
34
    def __init__(self, crop_size, resize_size=256, mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225),
                 interpolation=InterpolationMode.BILINEAR):
35
36

        self.transforms = transforms.Compose([
37
            transforms.Resize(resize_size, interpolation=interpolation),
38
39
40
41
42
43
44
            transforms.CenterCrop(crop_size),
            transforms.ToTensor(),
            transforms.Normalize(mean=mean, std=std),
        ])

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