|
a |
|
b/dsb2018_topcoders/selim/aug/composition.py |
|
|
1 |
import random |
|
|
2 |
import numpy as np |
|
|
3 |
|
|
|
4 |
class Compose: |
|
|
5 |
def __init__(self, transforms, prob=1.0): |
|
|
6 |
self.transforms = [t for t in transforms if t is not None] |
|
|
7 |
self.prob = prob |
|
|
8 |
|
|
|
9 |
def __call__(self, **data): |
|
|
10 |
if random.random() < self.prob: |
|
|
11 |
|
|
|
12 |
for t in self.transforms: |
|
|
13 |
data = t(**data) |
|
|
14 |
return data |
|
|
15 |
|
|
|
16 |
|
|
|
17 |
class OneOf: |
|
|
18 |
def __init__(self, transforms, prob=.5): |
|
|
19 |
self.transforms = transforms |
|
|
20 |
self.prob = prob |
|
|
21 |
|
|
|
22 |
def __call__(self, **data): |
|
|
23 |
if random.random() < self.prob: |
|
|
24 |
t = random.choice(self.transforms) |
|
|
25 |
t.prob = 1. |
|
|
26 |
data = t(**data) |
|
|
27 |
return data |
|
|
28 |
|
|
|
29 |
|
|
|
30 |
class OneOrOther: |
|
|
31 |
def __init__(self, first, second, prob=.5): |
|
|
32 |
self.first = first |
|
|
33 |
first.prob = 1. |
|
|
34 |
self.second = second |
|
|
35 |
second.prob = 1. |
|
|
36 |
self.prob = prob |
|
|
37 |
|
|
|
38 |
def __call__(self, **data): |
|
|
39 |
return self.first(**data) if random.random() < self.prob else self.second(**data) |
|
|
40 |
|
|
|
41 |
|
|
|
42 |
class GrayscaleOrColor: |
|
|
43 |
def __init__(self, color_transform, grayscale_transform): |
|
|
44 |
self.color_transform = color_transform |
|
|
45 |
self.grayscale_transform = grayscale_transform |
|
|
46 |
|
|
|
47 |
def __call__(self, **data): |
|
|
48 |
image = data['image'] |
|
|
49 |
grayscale = np.allclose(image[..., 0], image[..., 1], atol=0.001) and np.allclose(image[..., 1], image[..., 2], atol=0.001) |
|
|
50 |
if not grayscale: |
|
|
51 |
return self.color_transform(**data) |
|
|
52 |
else: |
|
|
53 |
return self.grayscale_transform(**data) |