-
Notifications
You must be signed in to change notification settings - Fork 1
/
misc.py
134 lines (91 loc) · 2.51 KB
/
misc.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import math
import os
from functools import wraps
import numpy as np
import pickle
from PIL import Image
import torch
def fix_random_state(seed):
pass
def exists(x):
return x is not None
def once(fn):
called = False
@wraps(fn)
def inner(x):
nonlocal called
if called:
return
called = True
return fn(x)
return inner
def default(val, d):
if exists(val):
return val
return d() if callable(d) else d
def cast_tuple(t, length = 1):
if isinstance(t, tuple):
return t
return ((t,) * length)
def divisible_by(numer, denom):
return (numer % denom) == 0
def identity(t, *args, **kwargs):
return t
def cycle(dl):
while True:
for data in dl:
yield data
def has_int_squareroot(num):
return (math.sqrt(num) ** 2) == num
def num_to_groups(num, divisor):
groups = num // divisor
remainder = num % divisor
arr = [divisor] * groups
if remainder > 0:
arr.append(remainder)
return arr
def convert_image_to_fn(img_type, image):
if image.mode != img_type:
return image.convert(img_type)
return image
def normalize_to_neg_one_to_one(img):
return img * 2 - 1
def unnormalize_to_zero_to_one(t):
return (t + 1) * 0.5
def num_to_groups(num, divisor):
groups = num // divisor
remainder = num % divisor
arr = [divisor] * groups
if remainder > 0:
arr.append(remainder)
return arr
def pkl_load(file_path):
with open(file_path, 'rb') as fr:
data = pickle.load(fr, encoding='bytes')
return data
def read_img(file_path):
return Image.open(file_path)
def dump_img(data, file_path):
if isinstance(data, np.ndarray):
image = Image.fromarray(data)
image.save(file_path)
class _GaussianMixture(object):
def __init__(self, means, variances, weights):
self._means = means
self._variances = variances
self._weights = weights
def sample(self):
indices = np.arange(0, len(self._means))
pos = np.random.choice(indices, p=self._weights)
mean = self._means[pos]
std = self._variances[pos]
return mean + std * np.random.randn(2)
def find_all_files(nested_dir):
results = []
for each in os.listdir(nested_dir):
path = os.path.join(nested_dir, each)
if os.path.isdir(path):
results.extend(find_all_files(path))
else:
results.append(path)
return results