如何有效地将ROS PointCloud2转换为pcl点云并在python中将其可视化

时间:2016-09-29 13:59:36

标签: python kinect ros point-clouds

我试图对ROS中的kinect中的pointcloud进行一些分割。截至目前我有这个:

import rospy
import pcl
from sensor_msgs.msg import PointCloud2
import sensor_msgs.point_cloud2 as pc2
def on_new_point_cloud(data):
    pc = pc2.read_points(data, skip_nans=True, field_names=("x", "y", "z"))
    pc_list = []
    for p in pc:
        pc_list.append( [p[0],p[1],p[2]] )

    p = pcl.PointCloud()
    p.from_list(pc_list)
    seg = p.make_segmenter()
    seg.set_model_type(pcl.SACMODEL_PLANE)
    seg.set_method_type(pcl.SAC_RANSAC)
    indices, model = seg.segment()

rospy.init_node('listener', anonymous=True)
rospy.Subscriber("/kinect2/hd/points", PointCloud2, on_new_point_cloud)
rospy.spin()

这似乎有效,但因为for循环而非常慢。 我的问题是:

1)我如何有效地将PointCloud2消息转换为pcl pointcloud

2)我如何形象化云。

3 个答案:

答案 0 :(得分:1)

在使用 Python3 的 Ubuntu 20.04 上,我使用以下内容:

import numpy as np
import pcl  # pip3 install python-pcl
import ros_numpy  # apt install ros-noetic-ros-numpy
import rosbag
import sensor_msgs

def convert_pc_msg_to_np(pc_msg):
    # Fix rosbag issues, see: https://github.com/eric-wieser/ros_numpy/issues/23
    pc_msg.__class__ = sensor_msgs.msg._PointCloud2.PointCloud2
    offset_sorted = {f.offset: f for f in pc_msg.fields}
    pc_msg.fields = [f for (_, f) in sorted(offset_sorted.items())]

    # Conversion from PointCloud2 msg to np array.
    pc_np = ros_numpy.point_cloud2.pointcloud2_to_xyz_array(pc_msg, remove_nans=True)
    pc_pcl = pcl.PointCloud(np.array(pc_np, dtype=np.float32))
    return pc_np, pc_pcl  # point cloud in numpy and pcl format

# Use a ros subscriber as you already suggested or is shown in the other
# answers to run it online :)

# To run it offline on a rosbag use:
for topic, msg, t in rosbag.Bag('/my/rosbag.bag').read_messages():
    if topic == "/my/cloud":
        pc_np, pc_pcl = convert_pc_msg_to_np(msg)


答案 1 :(得分:0)

这对我有用。我只是调整点云的大小,因为我的是一台有序的PC(512x x 512px)。我的代码改编自@Abdulbaki Aybakan-谢谢!!

我的代码:

pc = ros_numpy.numpify(pointcloud)
height = pc.shape[0]
width = pc.shape[1]
np_points = np.zeros((height * width, 3), dtype=np.float32)
np_points[:, 0] = np.resize(pc['x'], height * width)
np_points[:, 1] = np.resize(pc['y'], height * width)
np_points[:, 2] = np.resize(pc['z'], height * width)

要使用ros_numpy,必须克隆存储库:http://wiki.ros.org/ros_numpy

答案 2 :(得分:-1)

import rospy
import pcl
from sensor_msgs.msg import PointCloud2
import sensor_msgs.point_cloud2 as pc2
import ros_numpy

def callback(data):
    pc = ros_numpy.numpify(data)
    points=np.zeros((pc.shape[0],3))
    points[:,0]=pc['x']
    points[:,1]=pc['y']
    points[:,2]=pc['z']
    p = pcl.PointCloud(np.array(points, dtype=np.float32))

rospy.init_node('listener', anonymous=True)
rospy.Subscriber("/velodyne_points", PointCloud2, callback)
rospy.spin()

我希望使用ros_numpy模块首先转换为numpy数组,然后从该数组初始化点云。