Download ros_vizualizer.py from jacodd/SynthField: direct link, hf CLI and curl.
- Browser
- Download file 11.2 kB
-
https://huggingface.co/datasets/jacodd/SynthField/resolve/main/ros_vizualizer.py
- Command line
-
hf download hf://datasets/jacodd/SynthField/ros_vizualizer.py
-
curl -L -o ros_vizualizer.py https://huggingface.co/datasets/jacodd/SynthField/resolve/main/ros_vizualizer.py
11.2 kB
| import rclpy | |
| from rclpy.node import Node | |
| from sensor_msgs.msg import Image, Imu, PointCloud2 | |
| import sensor_msgs_py.point_cloud2 as pc2 | |
| from nav_msgs.msg import Odometry | |
| from std_msgs.msg import String | |
| import numpy as np | |
| import matplotlib.pyplot as plt | |
| from matplotlib.gridspec import GridSpec | |
| from mpl_toolkits.mplot3d import Axes3D | |
| import matplotlib.patches as mpatches | |
| import json | |
| import cv2 | |
| from cv_bridge import CvBridge | |
| from scipy.spatial.transform import Rotation as R | |
| class MultiSensorMonitor(Node): | |
| def __init__(self): | |
| super().__init__('multi_sensor_monitor') | |
| self.bridge = CvBridge() | |
| self.label_colors = {} | |
| self.class_name_to_color = { | |
| 'unlabeled': [0, 0, 0] | |
| } | |
| self.data = { | |
| 'bev_rgb': None, 'bev_sem': None, | |
| 'front_rgb': None, 'front_sem': None, 'front_depth': None, | |
| 'bev_labels': {}, | |
| 'front_labels': {}, | |
| 'odom_x': [], 'odom_y': [], | |
| 'imu_quat': [0.0, 0.0, 0.0, 1.0], | |
| 'lidar_points': None | |
| } | |
| # Subscribers | |
| self.create_subscription(Image, '/bev/rgb', self.cb_bev_rgb, 10) | |
| self.create_subscription(Image, '/bev/semantic_segmentation', self.cb_bev_sem, 10) | |
| self.create_subscription(String, '/bev/semantic_labels', self.cb_bev_labels, 10) | |
| self.create_subscription(Image, '/camera_front/rgb', self.cb_front_rgb, 10) | |
| self.create_subscription(Image, '/camera_front/semantic_segmentation', self.cb_front_sem, 10) | |
| self.create_subscription(Image, '/camera_front/depth', self.cb_front_depth, 10) | |
| self.create_subscription(String, '/camera_front/semantic_labels', self.cb_front_labels, 10) | |
| self.create_subscription(Odometry, '/odom', self.cb_odom, 10) | |
| self.create_subscription(Imu, '/imu', self.cb_imu, 10) | |
| self.create_subscription(PointCloud2, '/lidar_front/point_cloud', self.cb_lidar, 10) | |
| plt.ion() | |
| # 1. FIX: layout='constrained' resolve sobreposições e elimina espaços em branco inúteis. | |
| # Ajustado para 18x8 para casar melhor com o formato das imagens. | |
| self.fig = plt.figure(figsize=(18, 8), layout='constrained') | |
| gs = GridSpec(2, 4, figure=self.fig) | |
| self.ax_bev_rgb = self.fig.add_subplot(gs[0, 0]) | |
| self.ax_bev_sem = self.fig.add_subplot(gs[1, 0]) | |
| self.ax_f_rgb = self.fig.add_subplot(gs[0, 1]) | |
| self.ax_f_sem = self.fig.add_subplot(gs[1, 1]) | |
| self.ax_f_depth = self.fig.add_subplot(gs[1, 2]) | |
| self.ax_lidar = self.fig.add_subplot(gs[0, 2]) | |
| self.ax_odom = self.fig.add_subplot(gs[0, 3]) | |
| self.ax_imu = self.fig.add_subplot(gs[1, 3], projection='3d') | |
| self.cb_depth_bar = None | |
| self.cb_lidar_bar = None | |
| self.timer = self.create_timer(0.1, self.update_plot) | |
| def get_color(self, uid): | |
| if uid not in self.label_colors: | |
| np.random.seed(uid) | |
| self.label_colors[uid] = np.random.randint(0, 255, size=3).tolist() | |
| return self.label_colors[uid] | |
| def get_color_by_name(self, class_name): | |
| if class_name not in self.class_name_to_color: | |
| seed = sum(ord(c) for c in class_name) | |
| np.random.seed(seed) | |
| self.class_name_to_color[class_name] = np.random.randint(0, 255, size=3).tolist() | |
| return self.class_name_to_color[class_name] | |
| def cb_lidar(self, msg): | |
| points_gen = pc2.read_points(msg, field_names=("x", "y", "z"), skip_nans=True) | |
| pts_list = [(p[0], p[1], p[2]) for p in points_gen] | |
| if pts_list: | |
| self.data['lidar_points'] = np.array(pts_list, dtype=np.float32) | |
| else: | |
| self.data['lidar_points'] = None | |
| def cb_odom(self, msg): | |
| self.data['odom_x'].append(msg.pose.pose.position.x) | |
| self.data['odom_y'].append(msg.pose.pose.position.y) | |
| if len(self.data['odom_x']) > 1000: | |
| self.data['odom_x'].pop(0); self.data['odom_y'].pop(0) | |
| def cb_imu(self, msg): | |
| q = msg.orientation | |
| self.data['imu_quat'] = [q.x, q.y, q.z, q.w] | |
| def cb_bev_rgb(self, msg): self.data['bev_rgb'] = self.bridge.imgmsg_to_cv2(msg, "bgr8") | |
| def cb_bev_sem(self, msg): self.data['bev_sem'] = self.bridge.imgmsg_to_cv2(msg, "32SC1") | |
| def cb_front_rgb(self, msg): self.data['front_rgb'] = self.bridge.imgmsg_to_cv2(msg, "bgr8") | |
| def cb_front_sem(self, msg): self.data['front_sem'] = self.bridge.imgmsg_to_cv2(msg, "32SC1") | |
| def cb_bev_labels(self, msg): | |
| try: | |
| raw_data = json.loads(msg.data) | |
| self.data['bev_labels'] = {int(k): v['class'] for k, v in raw_data.items() if k.isdigit()} | |
| except Exception as e: | |
| pass | |
| def cb_front_labels(self, msg): | |
| try: | |
| raw_data = json.loads(msg.data) | |
| self.data['front_labels'] = {int(k): v['class'] for k, v in raw_data.items() if k.isdigit()} | |
| except Exception as e: | |
| pass | |
| def colorize_semantic(self, sem_img, label_map): | |
| if sem_img is None: return np.zeros((100, 100, 3), dtype=np.uint8) | |
| h, w = sem_img.shape | |
| color_img = np.zeros((h, w, 3), dtype=np.uint8) | |
| unique_ids = np.unique(sem_img) | |
| for uid in unique_ids: | |
| if uid == 0: continue | |
| class_name = label_map.get(uid, 'unknown') | |
| color_img[sem_img == uid] = self.get_color_by_name(class_name) | |
| return color_img | |
| def cb_front_depth(self, msg): | |
| depth_img = self.bridge.imgmsg_to_cv2(msg, "32FC1") | |
| self.data['front_depth'] = np.clip(depth_img, 0.0, 10.0) | |
| def update_plot(self): | |
| for ax in [self.ax_bev_rgb, self.ax_bev_sem, self.ax_odom, self.ax_f_rgb, | |
| self.ax_f_sem, self.ax_f_depth, self.ax_lidar]: | |
| ax.clear() | |
| self.ax_imu.cla() | |
| # --- BEV RGB & Semantic --- | |
| if self.data['bev_rgb'] is not None: | |
| self.ax_bev_rgb.imshow(cv2.cvtColor(self.data['bev_rgb'], cv2.COLOR_BGR2RGB)) | |
| self.ax_bev_rgb.set_xticks([]); self.ax_bev_rgb.set_yticks([]) | |
| self.ax_bev_rgb.set_title("BEV RGB") | |
| if self.data['bev_sem'] is not None: | |
| colored_bev = self.colorize_semantic(self.data['bev_sem'], self.data['bev_labels']) | |
| self.ax_bev_sem.imshow(colored_bev) | |
| self.ax_bev_sem.set_xticks([]); self.ax_bev_sem.set_yticks([]) | |
| self.ax_bev_sem.set_title("BEV Semantic") | |
| # --- Front RGB & Semantic --- | |
| if self.data['front_rgb'] is not None: | |
| self.ax_f_rgb.imshow(cv2.cvtColor(self.data['front_rgb'], cv2.COLOR_BGR2RGB)) | |
| self.ax_f_rgb.set_xticks([]); self.ax_f_rgb.set_yticks([]) | |
| self.ax_f_rgb.set_title("Front RGB") | |
| if self.data['front_sem'] is not None: | |
| colored_front = self.colorize_semantic(self.data['front_sem'], self.data['front_labels']) | |
| self.ax_f_sem.imshow(colored_front) | |
| self.ax_f_sem.set_xticks([]); self.ax_f_sem.set_yticks([]) | |
| self.ax_f_sem.set_title("Front Semantic") | |
| # --- Legenda Semântica Global --- | |
| legend_patches = [mpatches.Patch(color=np.array(col)/255.0, label=name) | |
| for name, col in self.class_name_to_color.items() if name != 'unlabeled'] | |
| if legend_patches: | |
| # Ancoragem ajustada para não quebrar o layout | |
| self.ax_f_sem.legend(handles=legend_patches, loc='center left', bbox_to_anchor=(1.02, 0.5), | |
| fontsize='8', title="Semantic Classes") | |
| # --- Depth Map --- | |
| if self.data['front_depth'] is not None: | |
| im_depth = self.ax_f_depth.imshow(self.data['front_depth'], cmap='magma', vmin=0, vmax=10) | |
| self.ax_f_depth.set_xticks([]); self.ax_f_depth.set_yticks([]) | |
| self.ax_f_depth.set_title("Front Depth") | |
| if self.cb_depth_bar is None: | |
| self.cb_depth_bar = self.fig.colorbar(im_depth, ax=self.ax_f_depth, fraction=0.046, pad=0.04) | |
| self.cb_depth_bar.set_label('Depth [m]') | |
| else: | |
| self.cb_depth_bar.update_normal(im_depth) | |
| # --- Lidar --- | |
| if self.data['lidar_points'] is not None: | |
| pts = self.data['lidar_points'] | |
| scat = self.ax_lidar.scatter(pts[:, 0], pts[:, 1], s=1, c=pts[:, 2], cmap='viridis', vmin=-2, vmax=3) | |
| self.ax_lidar.set_xlim([-1, 7]); self.ax_lidar.set_ylim([-7, 7]) | |
| self.ax_lidar.set_title("Lidar Top-Down") | |
| self.ax_lidar.set_xlabel('X [m]') | |
| self.ax_lidar.set_ylabel('Y [m]') | |
| self.ax_lidar.grid(True, linestyle=':', alpha=0.6) # Grade mais suave | |
| if self.cb_lidar_bar is None: | |
| self.cb_lidar_bar = self.fig.colorbar(scat, ax=self.ax_lidar, fraction=0.046, pad=0.04) | |
| self.cb_lidar_bar.set_label('Elevation (Z) [m]') | |
| else: | |
| self.cb_lidar_bar.update_normal(scat) | |
| # --- Odom --- | |
| if self.data['odom_x']: | |
| self.ax_odom.plot(self.data['odom_x'], self.data['odom_y'], 'b-', linewidth=1.5) | |
| self.ax_odom.plot(self.data['odom_x'][-1], self.data['odom_y'][-1], 'ro', markersize=5) | |
| self.ax_odom.set_title("Odom Path") | |
| self.ax_odom.set_xbound(0, 20) | |
| self.ax_odom.set_ybound(-1, 6) | |
| self.ax_odom.set_xlabel('X [m]') | |
| self.ax_odom.set_ylabel('Y [m]') | |
| self.ax_odom.grid(True, linestyle=':', alpha=0.6) # Grade mais suave | |
| # --- IMU 3D --- | |
| r = R.from_quat(self.data['imu_quat']) | |
| labels = ['X', 'Y', 'Z'] | |
| colors = ['r', 'g', 'b'] | |
| for i, (color, lbl) in enumerate(zip(colors, labels)): | |
| vec = np.zeros(3); vec[i] = 1 | |
| v_rot = r.apply(vec) | |
| 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) | |
| self.ax_imu.text(v_rot[0]*1.2, v_rot[1]*1.2, v_rot[2]*1.2, lbl, color=color, fontweight='bold') | |
| self.ax_imu.set_xlim([-1, 1]); self.ax_imu.set_ylim([-1, 1]); self.ax_imu.set_zlim([-1, 1]) | |
| self.ax_imu.set_title("IMU Orientation") | |
| # 2. FIX: Limpeza total da grade e fundo do eixo 3D | |
| self.ax_imu.grid(True) # Remove as dezenas de linhas transversais | |
| self.ax_imu.set_xticks([-1, 0, 1]) # Mostra apenas min, centro e max | |
| self.ax_imu.set_yticks([-1, 0, 1]) | |
| self.ax_imu.set_zticks([-1, 0, 1]) | |
| # Remove os painéis cinzas do fundo do eixo 3D deixando o fundo transparente/branco | |
| self.ax_imu.xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) | |
| self.ax_imu.yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) | |
| self.ax_imu.zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) | |
| plt.draw() | |
| plt.pause(0.001) | |
| def main(args=None): | |
| rclpy.init(args=args) | |
| node = MultiSensorMonitor() | |
| try: | |
| rclpy.spin(node) | |
| except KeyboardInterrupt: | |
| pass | |
| node.destroy_node() | |
| rclpy.shutdown() | |
| if __name__ == '__main__': | |
| main() |