-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathsave_clouds_from_bag
executable file
·164 lines (128 loc) · 7.48 KB
/
save_clouds_from_bag
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
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function
import rospy
from sensor_msgs.msg import PointCloud2
import yaml
from ros_numpy import msgify, numpify
import os
import numpy as np
from numpy.lib.recfunctions import structured_to_unstructured
import rosbag
from tqdm import tqdm
import image_geometry
import torch
from datasets.laserscan import SemLaserScan
from datasets.base_dataset import TRAVERSABILITY_COLOR_MAP
import open3d as o3d
pkg_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '../..'))
def find_nearest(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return array[idx], idx
def slots(msg):
"""Return message attributes (slots) as list."""
return [getattr(msg, var) for var in msg.__slots__]
class PointsProcessor:
def __init__(self, pc_topic='/points'):
self.pc_topic = rospy.get_param('~pointcloud_topic', pc_topic)
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
self.file_names = []
self.data_path = os.path.join(pkg_path, 'data', 'TraversabilityDataset', 'supervised')
self.points_path = os.path.join(self.data_path, 'clouds', pc_topic.split('/')[-1] + '_colored')
self.bag_file = rospy.get_param('~bag_file',
os.path.join(pkg_path,
'data/bags/traversability/marv/ugv_2022-08-12-15-18-34.bag')) # ugv_2022-08-12-15-30-22.bag
assert os.path.exists(self.bag_file)
self.camera_model = image_geometry.PinholeCameraModel()
self.data_fields = ['depth']
self.model = self.load_model()
self.scan = SemLaserScan(nclasses=2,
sem_color_dict=TRAVERSABILITY_COLOR_MAP,
project=True,
H=128, W=1024,
fov_up=45.0, fov_down=-45.0)
self.annotated_imgs_stamps = self.get_time_stamps(self.bag_file)
self.t_eps = rospy.get_param('~t_threshold', 0.1)
self.run(pc_topic)
def load_model(self):
model_weights = rospy.get_param('~weights',
'fcn_resnet101_lr_0.0001_bs_16_epoch_40_Rellis3DClouds_z_intensity_depth_travTrue_ftTrue_iou_0.54.pth')
self.data_fields = [f[1:-1] for f in ['_x_', '_y_', '_z_', '_intensity_', '_depth_'] if f in model_weights]
model_path = os.path.join(pkg_path, "config/weights/", "depth_cloud/%s" % model_weights)
assert os.path.exists(model_path)
model = torch.load(model_path, map_location=self.device)
model = model.eval()
return model
def get_time_stamps(self, bag_file):
if not os.path.exists(self.points_path):
os.mkdir(self.points_path)
bag_file = bag_file.split('/')[-1].replace('_points', '')
file_to_bag = yaml.safe_load(
open(os.path.join(self.data_path, 'correspondencies.yaml'), 'r'))
annotated_imgs_stamps = []
assert bag_file in file_to_bag.keys()
for camera_frame in file_to_bag[bag_file].keys():
for i, t in enumerate(file_to_bag[bag_file][camera_frame]):
fname = file_to_bag[bag_file][camera_frame][i]
secs = int(fname.split('_')[1].replace('s', ''))
nsecs = int(fname.split('_')[2].replace('n', '').replace('.jpg', ''))
annotated_imgs_stamps.append(rospy.Time(secs, nsecs).to_sec())
self.file_names.append(fname.replace('.jpg', '.pcd'))
assert len(self.file_names) == len(annotated_imgs_stamps)
rospy.loginfo('Found %s images annotated from bag file %s' % (len(annotated_imgs_stamps), bag_file))
return annotated_imgs_stamps
def run(self, pc_topic):
with rosbag.Bag(self.bag_file, 'r') as bag:
for (topic, pc_msg, ts) in tqdm(bag.read_messages(topics=str(pc_topic))):
pc_msg = PointCloud2(*slots(pc_msg))
assert isinstance(pc_msg, PointCloud2)
pc_stamp = pc_msg.header.stamp.to_sec()
rospy.logdebug('Point cloud time: %s' % pc_stamp)
closest_img_stamp, idx = find_nearest(self.annotated_imgs_stamps, pc_stamp)
t_diff = np.abs(pc_stamp - closest_img_stamp)
rospy.logdebug('Closest img time: %ds [sec], time difference: %s [sec]'
% (closest_img_stamp, t_diff))
if t_diff < self.t_eps:
if closest_img_stamp in self.annotated_imgs_stamps:
# save point cloud here
rospy.logdebug('Cloud fields: %s' % pc_msg.fields)
cloud = numpify(pc_msg)
rospy.loginfo('Saving cloud to %s' % os.path.join(self.points_path, self.file_names[idx]),)
# color point cloud with model predictions
points = structured_to_unstructured(cloud[['x', 'y', 'z']]).reshape((-1, 3))
self.scan.set_points(points=points, remissions=cloud['intensity'].reshape(-1,))
xyzid = {'x': self.scan.proj_xyz[..., 0], # (H x W)
'y': self.scan.proj_xyz[..., 1], # (H x W)
'z': self.scan.proj_xyz[..., 2], # (H x W)
'intensity': self.scan.proj_remission, # (H x W)
'depth': self.scan.proj_range} # (H x W)
# normalize intensity to be in the same format as in Rellis 3D
if xyzid['intensity'].max() > 1.0:
xyzid['intensity'] /= 2.0 ** 16
inpt = np.concatenate([xyzid[f][None] for f in self.data_fields], axis=0)
batch = torch.from_numpy(inpt).unsqueeze(0).to(self.device)
with torch.no_grad():
pred = self.model(batch)['out']
pred = torch.softmax(pred.squeeze(0), dim=0).cpu().numpy()
label_pred = np.argmax(pred, axis=0)
colors = self.scan.sem_color_lut[label_pred].reshape((-1, 3))
colors = colors / colors.max()
# create o3d point cloud and save pcd file
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(points)
pcd.colors = o3d.utility.Vector3dVector(colors)
# o3d.visualization.draw_geometries([pcd])
# np.savez(os.path.join(self.points_path, self.file_names[idx]), cloud)
o3d.io.write_point_cloud(os.path.join(self.points_path, self.file_names[idx]), pcd)
self.annotated_imgs_stamps.remove(closest_img_stamp)
self.file_names.pop(idx)
rospy.loginfo('Number of image timestamps to find annotations to: %s'
% len(self.annotated_imgs_stamps))
if len(self.annotated_imgs_stamps) == 0:
rospy.loginfo('All point clouds for image labels are found!')
exit()
if rospy.is_shutdown():
exit()
if __name__ == '__main__':
rospy.init_node('pc_saving_node', log_level=rospy.DEBUG)
proc = PointsProcessor(pc_topic=rospy.get_param('cloud_in', '/os_cloud_node/destaggered_points'))