-
Notifications
You must be signed in to change notification settings - Fork 3
/
dataflow.py
267 lines (221 loc) · 8.25 KB
/
dataflow.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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
import numpy as np
import sys
import os
from tensorpack.callbacks.base import Callback
from tensorpack.dataflow.base import RNGDataFlow
if os.name == 'nt':
from sdv_src.build.Release import sdv
else:
from sdv_src.build import sdv
from utils import SMPLModel, naive_read_pcd, sample_vertex_from_mesh
from tensorpack import *
from glob import glob
import visdom
from sklearn.decomposition import PCA
from sklearn.preprocessing import MinMaxScaler
import hydra
import matplotlib.pyplot as plt
cm = plt.get_cmap('jet')
def load_sdv_feature(pc, path, caching):
if not caching:
return np.array(sdv.compute(pc)).astype(np.float32)
if not os.path.exists(path):
feature = np.array(sdv.compute(pc)).astype(np.float32)
np.save(path, feature)
return feature
else:
return np.load(path)
name2id = {
'airplane': '02691156',
'chair': '03001627',
'table': '04379243'
}
class ShapeNetDataFlow(RNGDataFlow):
def __init__(self, cfg, split, training):
self.training = training
self.cfg = cfg
self.pcds = []
self.mesh_names = []
split_models = open(hydra.utils.to_absolute_path(split)).readlines()
split_models = [m.split('-')[-1].rstrip('\n') for m in split_models]
for fn in glob(os.path.join(hydra.utils.to_absolute_path(cfg.data.pcd_root), name2id[cfg.cat_name], '*.pcd')):
model_id = os.path.basename(fn).split('.')[0]
if model_id not in split_models:
continue
self.pcds.append(naive_read_pcd(fn)[0])
self.mesh_names.append(model_id)
if self.cfg.caching and not os.path.exists(hydra.utils.to_absolute_path(self.cfg.data.feature_cache)):
os.makedirs(hydra.utils.to_absolute_path(self.cfg.data.feature_cache))
def _setup_graph(self):
self.predictor = self.trainer.get_predictor(['pc', 'pc_feature'], ['encoder/z', 'encoder/feature', 'recon_pc'])
def __len__(self):
return len(self.pcds)
def __getitem__(self, idx):
pc = self.pcds[idx]
mesh_name = self.mesh_names[idx]
feature = load_sdv_feature(pc, os.path.join(hydra.utils.to_absolute_path(self.cfg.data.feature_cache), mesh_name + '.npy'), caching=self.cfg.caching)
return pc, feature
def __iter__(self):
shuffle_list = np.arange(len(self))
if self.training:
self.rng.shuffle(shuffle_list)
for idx in shuffle_list:
pc = self.pcds[idx]
mesh_name = self.mesh_names[idx]
feature = load_sdv_feature(pc, os.path.join(hydra.utils.to_absolute_path(self.cfg.data.feature_cache), mesh_name + '.npy'), caching=self.cfg.caching)
yield pc, feature
class VisDataFlow(ShapeNetDataFlow, Callback):
def __init__(self, *args, **kwargs):
super().__init__(*args)
self.vis = visdom.Visdom(port=kwargs['port'])
def _trigger(self):
z = []
emb = []
recon = []
pcs = []
features = []
for _ in range(2):
idx = np.random.randint(len(self))
pc = self.pcds[idx]
mesh_name = self.mesh_names[idx]
feature = load_sdv_feature(pc, os.path.join(self.cfg.data.feature_cache, mesh_name + '.npy'), caching=self.cfg.caching)
output = self.predictor(pc[None], feature[None])
z.append(output[0][0])
emb.append(output[1][0])
recon.append(output[2][0])
pcs.append(pc)
features.append(feature)
prob = z[0] > 0.5
label = np.ones((pcs[0].shape[0],), dtype=np.int)
if np.sum(prob.astype(np.float32)) > 0:
label[prob] = 2
self.vis.scatter(
X=pcs[0],
Y=label,
win=1,
opts=dict(
title='Detected keypoints'
),
)
self.vis.scatter(
X=recon[0],
win=2,
opts=dict(
markercolor=(z[0] * 255).astype(np.int),
title='Reconstruction'
),
)
rgb = np.array([cm(i * 255)[:3] for i in z[0]])
self.vis.scatter(
X=pcs[0],
win=3,
opts=dict(
markercolor=(rgb * 255).astype(np.int),
title='Keypoint Probability'
),
)
pca = PCA(n_components=3)
scaler = MinMaxScaler()
rgb = pca.fit_transform(emb[0])
rgb = scaler.fit_transform(rgb)
self.vis.scatter(
X=pcs[0],
win=4,
opts=dict(
markercolor=(rgb * 255).astype(np.int),
title='Embedding Prediction (Model 1)'
),
)
rgb = pca.transform(emb[1])
rgb = np.clip(scaler.transform(rgb), 0., 1.)
self.vis.scatter(
X=pcs[1],
win=5,
opts=dict(
markercolor=(rgb * 255).astype(np.int),
title='Embedding Prediction (Model 2)'
),
)
class SMPLDataFlow(RNGDataFlow):
def __init__(self, cfg, training, len):
self.training = training
self.cfg = cfg
self.smpl = SMPLModel(os.path.join(os.path.dirname(__file__), 'data/model.pkl'))
self.len = len
def _setup_graph(self):
self.predictor = self.trainer.get_predictor(['pc', 'pc_feature'], ['encoder/z', 'encoder/feature', 'recon_pc'])
def __len__(self):
return self.len
def __iter__(self):
# smpl dataflow
for _ in range(len(self)):
pose = (np.random.rand(*self.smpl.pose_shape) - 0.5) * 0.4
beta = (np.random.rand(*self.smpl.beta_shape) - 0.5) * 0.06
trans = np.zeros(self.smpl.trans_shape)
self.smpl.set_params(beta=beta, pose=pose, trans=trans)
pc, _, _, _, _ = sample_vertex_from_mesh(self.smpl.verts, self.smpl.faces, num_samples=self.cfg.num_points)
feature = np.array(sdv.compute(pc)).astype(np.float32)
yield pc, feature
class VisSMPLDataFlow(SMPLDataFlow, Callback):
def __init__(self, *args, **kwargs):
super().__init__(*args)
self.vis = visdom.Visdom(port=kwargs['port'])
def _trigger(self):
z = []
emb = []
recon = []
pcs = []
features = []
for _ in range(2):
pose = (np.random.rand(*self.smpl.pose_shape) - 0.5) * 0.4
beta = (np.random.rand(*self.smpl.beta_shape) - 0.5) * 0.06
trans = np.zeros(self.smpl.trans_shape)
self.smpl.set_params(beta=beta, pose=pose, trans=trans)
pc, _, _, _, _ = sample_vertex_from_mesh(self.smpl.verts, self.smpl.faces, num_samples=self.cfg.num_points)
feature = np.array(sdv.compute(pc)).astype(np.float32)
output = self.predictor(pc[None], feature[None])
z.append(output[0][0])
emb.append(output[1][0])
recon.append(output[2][0])
pcs.append(pc)
features.append(feature)
prob = z[0] > 0.5
label = np.ones((pcs[0].shape[0],), dtype=np.int)
if np.sum(prob.astype(np.float32)) > 0:
label[prob] = 2
self.vis.scatter(
X=pcs[0],
Y=label,
win=1,
)
self.vis.scatter(
X=recon[0],
win=2
)
self.vis.scatter(
X=pcs[0],
win=3,
opts=dict(
markercolor=(z[0] * 255).astype(np.int)
),
)
pca = PCA(n_components=3)
scaler = MinMaxScaler()
rgb = pca.fit_transform(emb[0])
rgb = scaler.fit_transform(rgb)
self.vis.scatter(
X=pcs[0],
win=4,
opts=dict(
markercolor=(rgb * 255).astype(np.int)
),
)
rgb = pca.transform(emb[1])
rgb = np.clip(scaler.transform(rgb), 0., 1.)
self.vis.scatter(
X=pcs[1],
win=5,
opts=dict(
markercolor=(rgb * 255).astype(np.int)
),
)