Skip to content

Commit 53cdded

Browse files
committed
add data-processing
1 parent bf60ab3 commit 53cdded

File tree

6 files changed

+515
-0
lines changed

6 files changed

+515
-0
lines changed

data_preprocess/IO.py

+187
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,187 @@
1+
#!/usr/bin/env python3.4
2+
3+
import os
4+
import re
5+
import numpy as np
6+
import uuid
7+
from scipy import misc
8+
import numpy as np
9+
from PIL import Image
10+
import sys
11+
12+
13+
def read(file):
14+
if file.endswith('.float3'): return readFloat(file)
15+
elif file.endswith('.flo'): return readFlow(file)
16+
elif file.endswith('.ppm'): return readImage(file)
17+
elif file.endswith('.pgm'): return readImage(file)
18+
elif file.endswith('.png'): return readImage(file)
19+
elif file.endswith('.jpg'): return readImage(file)
20+
elif file.endswith('.pfm'): return readPFM(file)[0]
21+
else: raise Exception('don\'t know how to read %s' % file)
22+
23+
def write(file, data):
24+
if file.endswith('.float3'): return writeFloat(file, data)
25+
elif file.endswith('.flo'): return writeFlow(file, data)
26+
elif file.endswith('.ppm'): return writeImage(file, data)
27+
elif file.endswith('.pgm'): return writeImage(file, data)
28+
elif file.endswith('.png'): return writeImage(file, data)
29+
elif file.endswith('.jpg'): return writeImage(file, data)
30+
elif file.endswith('.pfm'): return writePFM(file, data)
31+
else: raise Exception('don\'t know how to write %s' % file)
32+
33+
def readPFM(file):
34+
file = open(file, 'rb')
35+
36+
color = None
37+
width = None
38+
height = None
39+
scale = None
40+
endian = None
41+
42+
header = file.readline().rstrip()
43+
if header.decode("ascii") == 'PF':
44+
color = True
45+
elif header.decode("ascii") == 'Pf':
46+
color = False
47+
else:
48+
raise Exception('Not a PFM file.')
49+
50+
dim_match = re.match(r'^(\d+)\s(\d+)\s$', file.readline().decode("ascii"))
51+
if dim_match:
52+
width, height = list(map(int, dim_match.groups()))
53+
else:
54+
raise Exception('Malformed PFM header.')
55+
56+
scale = float(file.readline().decode("ascii").rstrip())
57+
if scale < 0: # little-endian
58+
endian = '<'
59+
scale = -scale
60+
else:
61+
endian = '>' # big-endian
62+
63+
data = np.fromfile(file, endian + 'f')
64+
shape = (height, width, 3) if color else (height, width)
65+
66+
data = np.reshape(data, shape)
67+
data = np.flipud(data)
68+
return data, scale
69+
70+
def writePFM(file, image, scale=1):
71+
file = open(file, 'wb')
72+
73+
color = None
74+
75+
if image.dtype.name != 'float32':
76+
raise Exception('Image dtype must be float32.')
77+
78+
image = np.flipud(image)
79+
80+
if len(image.shape) == 3 and image.shape[2] == 3: # color image
81+
color = True
82+
elif len(image.shape) == 2 or len(image.shape) == 3 and image.shape[2] == 1: # greyscale
83+
color = False
84+
else:
85+
raise Exception('Image must have H x W x 3, H x W x 1 or H x W dimensions.')
86+
87+
file.write('PF\n' if color else 'Pf\n'.encode())
88+
file.write('%d %d\n'.encode() % (image.shape[1], image.shape[0]))
89+
90+
endian = image.dtype.byteorder
91+
92+
if endian == '<' or endian == '=' and sys.byteorder == 'little':
93+
scale = -scale
94+
95+
file.write('%f\n'.encode() % scale)
96+
97+
image.tofile(file)
98+
99+
def readFlow(name):
100+
if name.endswith('.pfm') or name.endswith('.PFM'):
101+
return readPFM(name)[0][:,:,0:2]
102+
103+
f = open(name, 'rb')
104+
105+
header = f.read(4)
106+
if header.decode("utf-8") != 'PIEH':
107+
raise Exception('Flow file header does not contain PIEH')
108+
109+
width = np.fromfile(f, np.int32, 1).squeeze()
110+
height = np.fromfile(f, np.int32, 1).squeeze()
111+
112+
flow = np.fromfile(f, np.float32, width * height * 2).reshape((height, width, 2))
113+
114+
return flow.astype(np.float32)
115+
116+
def readImage(name):
117+
if name.endswith('.pfm') or name.endswith('.PFM'):
118+
data = readPFM(name)[0]
119+
if len(data.shape)==3:
120+
return data[:,:,0:3]
121+
else:
122+
return data
123+
124+
return misc.imread(name)
125+
126+
def writeImage(name, data):
127+
if name.endswith('.pfm') or name.endswith('.PFM'):
128+
return writePFM(name, data, 1)
129+
130+
return misc.imsave(name, data)
131+
132+
def writeFlow(name, flow):
133+
f = open(name, 'wb')
134+
f.write('PIEH'.encode('utf-8'))
135+
np.array([flow.shape[1], flow.shape[0]], dtype=np.int32).tofile(f)
136+
flow = flow.astype(np.float32)
137+
flow.tofile(f)
138+
139+
def readFloat(name):
140+
f = open(name, 'rb')
141+
142+
if(f.readline().decode("utf-8")) != 'float\n':
143+
raise Exception('float file %s did not contain <float> keyword' % name)
144+
145+
dim = int(f.readline())
146+
147+
dims = []
148+
count = 1
149+
for i in range(0, dim):
150+
d = int(f.readline())
151+
dims.append(d)
152+
count *= d
153+
154+
dims = list(reversed(dims))
155+
156+
data = np.fromfile(f, np.float32, count).reshape(dims)
157+
if dim > 2:
158+
data = np.transpose(data, (2, 1, 0))
159+
data = np.transpose(data, (1, 0, 2))
160+
161+
return data
162+
163+
def writeFloat(name, data):
164+
f = open(name, 'wb')
165+
166+
dim=len(data.shape)
167+
if dim>3:
168+
raise Exception('bad float file dimension: %d' % dim)
169+
170+
f.write(('float\n').encode('ascii'))
171+
f.write(('%d\n' % dim).encode('ascii'))
172+
173+
if dim == 1:
174+
f.write(('%d\n' % data.shape[0]).encode('ascii'))
175+
else:
176+
f.write(('%d\n' % data.shape[1]).encode('ascii'))
177+
f.write(('%d\n' % data.shape[0]).encode('ascii'))
178+
for i in range(2, dim):
179+
f.write(('%d\n' % data.shape[i]).encode('ascii'))
180+
181+
data = data.astype(np.float32)
182+
if dim==2:
183+
data.tofile(f)
184+
185+
else:
186+
np.transpose(data, (2, 0, 1)).tofile(f)
187+
+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import numpy as np
2+
3+
4+
def next_pixel2pc(flow, disparity, save_path=None, f=-1050., cx=479.5, cy=269.5):
5+
height, width = disparity.shape
6+
7+
BASELINE = 1.0
8+
depth = -1. * f * BASELINE / disparity
9+
10+
x = ((np.tile(np.arange(width, dtype=np.float32)[None, :], (height, 1)) - cx + flow[..., 0]) * -1. / disparity)[:,
11+
:, None]
12+
y = ((np.tile(np.arange(height, dtype=np.float32)[:, None], (1, width)) - cy + flow[..., 1]) * 1. / disparity)[:,
13+
:, None]
14+
pc = np.concatenate((x, y, depth[:, :, None]), axis=-1)
15+
16+
if save_path is not None:
17+
np.save(save_path, pc)
18+
return pc
19+
20+
21+
def pixel2pc(disparity, save_path=None, f=-1050., cx=479.5, cy=269.5):
22+
height, width = disparity.shape
23+
24+
BASELINE = 1.0
25+
depth = -1. * f * BASELINE / disparity
26+
27+
x = ((np.tile(np.arange(width, dtype=np.float32)[None, :], (height, 1)) - cx) * -1. / disparity)[:, :, None]
28+
y = ((np.tile(np.arange(height, dtype=np.float32)[:, None], (1, width)) - cy) * 1. / disparity)[:, :, None]
29+
pc = np.concatenate((x, y, depth[:, :, None]), axis=-1)
30+
31+
if save_path is not None:
32+
np.save(save_path, pc)
33+
return pc

data_preprocess/kitti_utils.py

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import numpy as np
2+
import png
3+
4+
5+
def pixel2xyz(depth, P_rect, px=None, py=None):
6+
assert P_rect[0,1] == 0
7+
assert P_rect[1,0] == 0
8+
assert P_rect[2,0] == 0
9+
assert P_rect[2,1] == 0
10+
assert P_rect[0,0] == P_rect[1,1]
11+
focal_length_pixel = P_rect[0,0]
12+
13+
height, width = depth.shape[:2]
14+
if px is None:
15+
px = np.tile(np.arange(width, dtype=np.float32)[None, :], (height, 1))
16+
if py is None:
17+
py = np.tile(np.arange(height, dtype=np.float32)[:, None], (1, width))
18+
const_x = P_rect[0,2] * depth + P_rect[0,3]
19+
const_y = P_rect[1,2] * depth + P_rect[1,3]
20+
21+
x = ((px * (depth + P_rect[2,3]) - const_x) / focal_length_pixel) [:, :, None]
22+
y = ((py * (depth + P_rect[2,3]) - const_y) / focal_length_pixel) [:, :, None]
23+
pc = np.concatenate((x, y, depth[:, :, None]), axis=-1)
24+
25+
pc[..., :2] *= -1.
26+
return pc
27+
28+
29+
def load_uint16PNG(fpath):
30+
reader = png.Reader(fpath)
31+
pngdata = reader.read()
32+
px_array = np.vstack( map(np.uint16, pngdata[2]) )
33+
if pngdata[3]['planes'] == 3:
34+
width, height = pngdata[:2]
35+
px_array = px_array.reshape(height, width, 3)
36+
return px_array
37+
38+
39+
def load_disp(fpath):
40+
# A 0 value indicates an invalid pixel (ie, no
41+
# ground truth exists, or the estimation algorithm didn't produce an estimate
42+
# for that pixel).
43+
array = load_uint16PNG(fpath)
44+
valid = array > 0
45+
disp = array.astype(np.float32) / 256.0
46+
disp[np.logical_not(valid)] = -1.
47+
return disp, valid
48+
49+
50+
def load_op_flow(fpath):
51+
array = load_uint16PNG(fpath)
52+
valid = array[..., -1] == 1
53+
array = array.astype(np.float32)
54+
flow = (array[..., :-1] - 2**15) / 64.
55+
return flow, valid
56+
57+
58+
def disp_2_depth(disparity, valid_disp, FOCAL_LENGTH_PIXEL):
59+
BASELINE = 0.54
60+
depth = FOCAL_LENGTH_PIXEL * BASELINE / (disparity + 1e-5)
61+
depth[np.logical_not(valid_disp)] = -1.
62+
return depth
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import numpy as np
2+
import sys, os
3+
import os.path as osp
4+
from multiprocessing import Pool
5+
import argparse
6+
7+
import IO
8+
from flyingthings3d_utils import *
9+
10+
parser = argparse.ArgumentParser()
11+
parser.add_argument('--raw_data_path', type=str, help="path to the raw data")
12+
parser.add_argument('--save_path', type=str, help="save path")
13+
parser.add_argument('--only_save_near_pts', dest='save_near', action='store_true',
14+
help='only save near points to save disk space')
15+
16+
args = parser.parse_args()
17+
root_path = args.raw_data_path
18+
save_path = args.save_path
19+
# root_path = osp.abspath('/root/share/data/FlyingThings3D_subset/FlyingThings3D_subset/')
20+
# truenas_path = osp.abspath('/root/share/data/FlyingThings3D_subset_processed_full')
21+
# m2t_path = osp.abspath('/m2t/FlyingThings3D_subset_processed_full')
22+
23+
splits = ['train', 'val']
24+
25+
26+
def process_one_file(params):
27+
try:
28+
#import ipdb; ipdb.set_trace()
29+
train_val, fname = params
30+
31+
save_folder_path = osp.join(save_path, train_val, fname)
32+
os.makedirs(save_folder_path, exist_ok=True)
33+
34+
disp1 = IO.read(osp.join(root_path, train_val, 'disparity', 'left', fname + '.pfm'))
35+
disp1_occ = IO.read(osp.join(root_path, train_val, 'disparity_occlusions', 'left', fname + '.png'))
36+
disp1_change = IO.read(
37+
osp.join(root_path, train_val, 'disparity_change', 'left', 'into_future', fname + '.pfm'))
38+
flow = IO.read(osp.join(root_path, train_val, 'flow', 'left', 'into_future', fname + '.flo'))
39+
flow_occ = IO.read(osp.join(root_path, train_val, 'flow_occlusions', 'left', 'into_future', fname + '.png'))
40+
41+
pc1 = pixel2pc(disp1)
42+
pc2 = next_pixel2pc(flow, disp1 + disp1_change)
43+
44+
if pc1[..., -1].max() > 0 or pc2[..., -1].max() > 0:
45+
print('z > 0', train_val, fname, pc1[..., -1].max(), pc1[..., -1].min(), pc2[..., -1].max(),
46+
pc2[..., -1].min())
47+
48+
valid_mask = np.logical_and(disp1_occ == 0, flow_occ == 0)
49+
50+
pc1 = pc1[valid_mask]
51+
pc2 = pc2[valid_mask]
52+
53+
if not args.save_near:
54+
np.save(osp.join(save_folder_path, 'pc1.npy'), pc1)
55+
np.save(osp.join(save_folder_path, 'pc2.npy'), pc2)
56+
else:
57+
near_mask = np.logical_and(pc1[..., -1] > -35., pc2[..., -1] > -35.)
58+
np.save(osp.join(save_folder_path, 'pc1.npy'), pc1[near_mask])
59+
np.save(osp.join(save_folder_path, 'pc2.npy'), pc2[near_mask])
60+
61+
except Exception as ex:
62+
print('error in addressing params', params, 'see exception:')
63+
print(ex)
64+
sys.stdout.flush()
65+
return
66+
67+
68+
if __name__ == '__main__':
69+
param_list = []
70+
for train_val in splits:
71+
tmp_path = osp.join(root_path, train_val, 'disparity_change', 'left', 'into_future')
72+
param_list.extend([(train_val, item.split('.')[0]) for item in os.listdir(tmp_path)])
73+
74+
#process_one_file(param_list[0])
75+
76+
pool = Pool(4)
77+
pool.map(process_one_file, param_list)
78+
pool.close()
79+
pool.join()
80+
81+
print('Finish all!')

0 commit comments

Comments
 (0)