-
Notifications
You must be signed in to change notification settings - Fork 11
/
data_augment.py
72 lines (54 loc) · 2.26 KB
/
data_augment.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import random
import torchvision.transforms as transforms
import torchvision.transforms.functional as F
class PairRandomCrop(transforms.RandomCrop):
def __call__(self, image, label):
if self.padding is not None:
image = F.pad(image, self.padding, self.fill, self.padding_mode)
label = F.pad(label, self.padding, self.fill, self.padding_mode)
# pad the width if needed
if self.pad_if_needed and image.size[0] < self.size[1]:
image = F.pad(image, (self.size[1] - image.size[0], 0), self.fill, self.padding_mode)
label = F.pad(label, (self.size[1] - label.size[0], 0), self.fill, self.padding_mode)
# pad the height if needed
if self.pad_if_needed and image.size[1] < self.size[0]:
image = F.pad(image, (0, self.size[0] - image.size[1]), self.fill, self.padding_mode)
label = F.pad(label, (0, self.size[0] - image.size[1]), self.fill, self.padding_mode)
i, j, h, w = self.get_params(image, self.size)
return F.crop(image, i, j, h, w), F.crop(label, i, j, h, w)
class PairCompose(transforms.Compose):
def __call__(self, image, label):
for t in self.transforms:
image, label = t(image, label)
return image, label
class PairRandomHorizontalFilp(transforms.RandomHorizontalFlip):
def __call__(self, img, label):
"""
Args:
img (PIL Image): Image to be flipped.
Returns:
PIL Image: Randomly flipped image.
"""
if random.random() < self.p:
return F.hflip(img), F.hflip(label)
return img, label
class PairRandomVerticalFlip(transforms.RandomVerticalFlip):
def __call__(self, img, label):
"""
Args:
img (PIL Image): Image to be flipped.
Returns:
PIL Image: Randomly flipped image.
"""
if random.random() < self.p:
return F.vflip(img), F.vflip(label)
return img, label
class PairToTensor(transforms.ToTensor):
def __call__(self, pic, label):
"""
Args:
pic (PIL Image or numpy.ndarray): Image to be converted to tensor.
Returns:
Tensor: Converted image.
"""
return F.to_tensor(pic), F.to_tensor(label)