jacodd commited on
Commit
96930e3
·
verified ·
1 Parent(s): 27516ff

Upload ros_vizualizer.py

Browse files
Files changed (1) hide show
  1. ros_vizualizer.py +250 -0
ros_vizualizer.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import rclpy
2
+ from rclpy.node import Node
3
+ from sensor_msgs.msg import Image, Imu, PointCloud2
4
+ import sensor_msgs_py.point_cloud2 as pc2
5
+ from nav_msgs.msg import Odometry
6
+ from std_msgs.msg import String
7
+ import numpy as np
8
+ import matplotlib.pyplot as plt
9
+ from matplotlib.gridspec import GridSpec
10
+ from mpl_toolkits.mplot3d import Axes3D
11
+ import matplotlib.patches as mpatches
12
+ import json
13
+ import cv2
14
+ from cv_bridge import CvBridge
15
+ from scipy.spatial.transform import Rotation as R
16
+
17
+ class MultiSensorMonitor(Node):
18
+ def __init__(self):
19
+ super().__init__('multi_sensor_monitor')
20
+ self.bridge = CvBridge()
21
+
22
+ self.label_colors = {}
23
+ self.class_name_to_color = {
24
+ 'unlabeled': [0, 0, 0]
25
+ }
26
+
27
+ self.data = {
28
+ 'bev_rgb': None, 'bev_sem': None,
29
+ 'front_rgb': None, 'front_sem': None, 'front_depth': None,
30
+ 'bev_labels': {},
31
+ 'front_labels': {},
32
+ 'odom_x': [], 'odom_y': [],
33
+ 'imu_quat': [0.0, 0.0, 0.0, 1.0],
34
+ 'lidar_points': None
35
+ }
36
+
37
+ # Subscribers
38
+ self.create_subscription(Image, '/bev/rgb', self.cb_bev_rgb, 10)
39
+ self.create_subscription(Image, '/bev/semantic_segmentation', self.cb_bev_sem, 10)
40
+ self.create_subscription(String, '/bev/semantic_labels', self.cb_bev_labels, 10)
41
+ self.create_subscription(Image, '/camera_front/rgb', self.cb_front_rgb, 10)
42
+ self.create_subscription(Image, '/camera_front/semantic_segmentation', self.cb_front_sem, 10)
43
+ self.create_subscription(Image, '/camera_front/depth', self.cb_front_depth, 10)
44
+ self.create_subscription(String, '/camera_front/semantic_labels', self.cb_front_labels, 10)
45
+ self.create_subscription(Odometry, '/odom', self.cb_odom, 10)
46
+ self.create_subscription(Imu, '/imu', self.cb_imu, 10)
47
+ self.create_subscription(PointCloud2, '/lidar_front/point_cloud', self.cb_lidar, 10)
48
+
49
+ plt.ion()
50
+ # 1. FIX: layout='constrained' resolve sobreposições e elimina espaços em branco inúteis.
51
+ # Ajustado para 18x8 para casar melhor com o formato das imagens.
52
+ self.fig = plt.figure(figsize=(18, 8), layout='constrained')
53
+ gs = GridSpec(2, 4, figure=self.fig)
54
+
55
+ self.ax_bev_rgb = self.fig.add_subplot(gs[0, 0])
56
+ self.ax_bev_sem = self.fig.add_subplot(gs[1, 0])
57
+ self.ax_f_rgb = self.fig.add_subplot(gs[0, 1])
58
+ self.ax_f_sem = self.fig.add_subplot(gs[1, 1])
59
+ self.ax_f_depth = self.fig.add_subplot(gs[1, 2])
60
+ self.ax_lidar = self.fig.add_subplot(gs[0, 2])
61
+ self.ax_odom = self.fig.add_subplot(gs[0, 3])
62
+ self.ax_imu = self.fig.add_subplot(gs[1, 3], projection='3d')
63
+
64
+ self.cb_depth_bar = None
65
+ self.cb_lidar_bar = None
66
+
67
+ self.timer = self.create_timer(0.1, self.update_plot)
68
+
69
+ def get_color(self, uid):
70
+ if uid not in self.label_colors:
71
+ np.random.seed(uid)
72
+ self.label_colors[uid] = np.random.randint(0, 255, size=3).tolist()
73
+ return self.label_colors[uid]
74
+
75
+ def get_color_by_name(self, class_name):
76
+ if class_name not in self.class_name_to_color:
77
+ seed = sum(ord(c) for c in class_name)
78
+ np.random.seed(seed)
79
+ self.class_name_to_color[class_name] = np.random.randint(0, 255, size=3).tolist()
80
+ return self.class_name_to_color[class_name]
81
+
82
+ def cb_lidar(self, msg):
83
+ points_gen = pc2.read_points(msg, field_names=("x", "y", "z"), skip_nans=True)
84
+ pts_list = [(p[0], p[1], p[2]) for p in points_gen]
85
+ if pts_list:
86
+ self.data['lidar_points'] = np.array(pts_list, dtype=np.float32)
87
+ else:
88
+ self.data['lidar_points'] = None
89
+
90
+ def cb_odom(self, msg):
91
+ self.data['odom_x'].append(msg.pose.pose.position.x)
92
+ self.data['odom_y'].append(msg.pose.pose.position.y)
93
+ if len(self.data['odom_x']) > 1000:
94
+ self.data['odom_x'].pop(0); self.data['odom_y'].pop(0)
95
+
96
+ def cb_imu(self, msg):
97
+ q = msg.orientation
98
+ self.data['imu_quat'] = [q.x, q.y, q.z, q.w]
99
+
100
+ def cb_bev_rgb(self, msg): self.data['bev_rgb'] = self.bridge.imgmsg_to_cv2(msg, "bgr8")
101
+ def cb_bev_sem(self, msg): self.data['bev_sem'] = self.bridge.imgmsg_to_cv2(msg, "32SC1")
102
+ def cb_front_rgb(self, msg): self.data['front_rgb'] = self.bridge.imgmsg_to_cv2(msg, "bgr8")
103
+ def cb_front_sem(self, msg): self.data['front_sem'] = self.bridge.imgmsg_to_cv2(msg, "32SC1")
104
+
105
+ def cb_bev_labels(self, msg):
106
+ try:
107
+ raw_data = json.loads(msg.data)
108
+ self.data['bev_labels'] = {int(k): v['class'] for k, v in raw_data.items() if k.isdigit()}
109
+ except Exception as e:
110
+ pass
111
+
112
+ def cb_front_labels(self, msg):
113
+ try:
114
+ raw_data = json.loads(msg.data)
115
+ self.data['front_labels'] = {int(k): v['class'] for k, v in raw_data.items() if k.isdigit()}
116
+ except Exception as e:
117
+ pass
118
+
119
+ def colorize_semantic(self, sem_img, label_map):
120
+ if sem_img is None: return np.zeros((100, 100, 3), dtype=np.uint8)
121
+ h, w = sem_img.shape
122
+ color_img = np.zeros((h, w, 3), dtype=np.uint8)
123
+ unique_ids = np.unique(sem_img)
124
+ for uid in unique_ids:
125
+ if uid == 0: continue
126
+ class_name = label_map.get(uid, 'unknown')
127
+ color_img[sem_img == uid] = self.get_color_by_name(class_name)
128
+ return color_img
129
+
130
+ def cb_front_depth(self, msg):
131
+ depth_img = self.bridge.imgmsg_to_cv2(msg, "32FC1")
132
+ self.data['front_depth'] = np.clip(depth_img, 0.0, 10.0)
133
+
134
+ def update_plot(self):
135
+ for ax in [self.ax_bev_rgb, self.ax_bev_sem, self.ax_odom, self.ax_f_rgb,
136
+ self.ax_f_sem, self.ax_f_depth, self.ax_lidar]:
137
+ ax.clear()
138
+ self.ax_imu.cla()
139
+
140
+ # --- BEV RGB & Semantic ---
141
+ if self.data['bev_rgb'] is not None:
142
+ self.ax_bev_rgb.imshow(cv2.cvtColor(self.data['bev_rgb'], cv2.COLOR_BGR2RGB))
143
+ self.ax_bev_rgb.set_xticks([]); self.ax_bev_rgb.set_yticks([])
144
+ self.ax_bev_rgb.set_title("BEV RGB")
145
+
146
+ if self.data['bev_sem'] is not None:
147
+ colored_bev = self.colorize_semantic(self.data['bev_sem'], self.data['bev_labels'])
148
+ self.ax_bev_sem.imshow(colored_bev)
149
+ self.ax_bev_sem.set_xticks([]); self.ax_bev_sem.set_yticks([])
150
+ self.ax_bev_sem.set_title("BEV Semantic")
151
+
152
+ # --- Front RGB & Semantic ---
153
+ if self.data['front_rgb'] is not None:
154
+ self.ax_f_rgb.imshow(cv2.cvtColor(self.data['front_rgb'], cv2.COLOR_BGR2RGB))
155
+ self.ax_f_rgb.set_xticks([]); self.ax_f_rgb.set_yticks([])
156
+ self.ax_f_rgb.set_title("Front RGB")
157
+
158
+ if self.data['front_sem'] is not None:
159
+ colored_front = self.colorize_semantic(self.data['front_sem'], self.data['front_labels'])
160
+ self.ax_f_sem.imshow(colored_front)
161
+ self.ax_f_sem.set_xticks([]); self.ax_f_sem.set_yticks([])
162
+ self.ax_f_sem.set_title("Front Semantic")
163
+
164
+ # --- Legenda Semântica Global ---
165
+ legend_patches = [mpatches.Patch(color=np.array(col)/255.0, label=name)
166
+ for name, col in self.class_name_to_color.items() if name != 'unlabeled']
167
+ if legend_patches:
168
+ # Ancoragem ajustada para não quebrar o layout
169
+ self.ax_f_sem.legend(handles=legend_patches, loc='center left', bbox_to_anchor=(1.02, 0.5),
170
+ fontsize='8', title="Semantic Classes")
171
+
172
+ # --- Depth Map ---
173
+ if self.data['front_depth'] is not None:
174
+ im_depth = self.ax_f_depth.imshow(self.data['front_depth'], cmap='magma', vmin=0, vmax=10)
175
+ self.ax_f_depth.set_xticks([]); self.ax_f_depth.set_yticks([])
176
+ self.ax_f_depth.set_title("Front Depth")
177
+
178
+ if self.cb_depth_bar is None:
179
+ self.cb_depth_bar = self.fig.colorbar(im_depth, ax=self.ax_f_depth, fraction=0.046, pad=0.04)
180
+ self.cb_depth_bar.set_label('Depth [m]')
181
+ else:
182
+ self.cb_depth_bar.update_normal(im_depth)
183
+
184
+ # --- Lidar ---
185
+ if self.data['lidar_points'] is not None:
186
+ pts = self.data['lidar_points']
187
+ scat = self.ax_lidar.scatter(pts[:, 0], pts[:, 1], s=1, c=pts[:, 2], cmap='viridis', vmin=-2, vmax=3)
188
+ self.ax_lidar.set_xlim([-1, 7]); self.ax_lidar.set_ylim([-7, 7])
189
+ self.ax_lidar.set_title("Lidar Top-Down")
190
+ self.ax_lidar.set_xlabel('X [m]')
191
+ self.ax_lidar.set_ylabel('Y [m]')
192
+ self.ax_lidar.grid(True, linestyle=':', alpha=0.6) # Grade mais suave
193
+
194
+ if self.cb_lidar_bar is None:
195
+ self.cb_lidar_bar = self.fig.colorbar(scat, ax=self.ax_lidar, fraction=0.046, pad=0.04)
196
+ self.cb_lidar_bar.set_label('Elevation (Z) [m]')
197
+ else:
198
+ self.cb_lidar_bar.update_normal(scat)
199
+
200
+ # --- Odom ---
201
+ if self.data['odom_x']:
202
+ self.ax_odom.plot(self.data['odom_x'], self.data['odom_y'], 'b-', linewidth=1.5)
203
+ self.ax_odom.plot(self.data['odom_x'][-1], self.data['odom_y'][-1], 'ro', markersize=5)
204
+ self.ax_odom.set_title("Odom Path")
205
+ self.ax_odom.set_xbound(0, 20)
206
+ self.ax_odom.set_ybound(-1, 6)
207
+ self.ax_odom.set_xlabel('X [m]')
208
+ self.ax_odom.set_ylabel('Y [m]')
209
+ self.ax_odom.grid(True, linestyle=':', alpha=0.6) # Grade mais suave
210
+
211
+ # --- IMU 3D ---
212
+ r = R.from_quat(self.data['imu_quat'])
213
+ labels = ['X', 'Y', 'Z']
214
+ colors = ['r', 'g', 'b']
215
+
216
+ for i, (color, lbl) in enumerate(zip(colors, labels)):
217
+ vec = np.zeros(3); vec[i] = 1
218
+ v_rot = r.apply(vec)
219
+ self.ax_imu.quiver(0, 0, 0, v_rot[0], v_rot[1], v_rot[2], color=color, arrow_length_ratio=0.15, linewidth=2)
220
+ self.ax_imu.text(v_rot[0]*1.2, v_rot[1]*1.2, v_rot[2]*1.2, lbl, color=color, fontweight='bold')
221
+
222
+ self.ax_imu.set_xlim([-1, 1]); self.ax_imu.set_ylim([-1, 1]); self.ax_imu.set_zlim([-1, 1])
223
+ self.ax_imu.set_title("IMU Orientation")
224
+
225
+ # 2. FIX: Limpeza total da grade e fundo do eixo 3D
226
+ self.ax_imu.grid(True) # Remove as dezenas de linhas transversais
227
+ self.ax_imu.set_xticks([-1, 0, 1]) # Mostra apenas min, centro e max
228
+ self.ax_imu.set_yticks([-1, 0, 1])
229
+ self.ax_imu.set_zticks([-1, 0, 1])
230
+
231
+ # Remove os painéis cinzas do fundo do eixo 3D deixando o fundo transparente/branco
232
+ self.ax_imu.xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
233
+ self.ax_imu.yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
234
+ self.ax_imu.zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
235
+
236
+ plt.draw()
237
+ plt.pause(0.001)
238
+
239
+ def main(args=None):
240
+ rclpy.init(args=args)
241
+ node = MultiSensorMonitor()
242
+ try:
243
+ rclpy.spin(node)
244
+ except KeyboardInterrupt:
245
+ pass
246
+ node.destroy_node()
247
+ rclpy.shutdown()
248
+
249
+ if __name__ == '__main__':
250
+ main()