1、首先安装几个必要的库r,创立py文件,bag2bin.py将以下代码填入,python bag2bin.py即可得到bin文件。
import os
import rosbag
import sensor_msgs.point_cloud2 as pc2
import numpy as np
def bag_to_bin(bag_file, output_dir, topic):
# 创建输出目录
if not os.path.exists(output_dir):
os.makedirs(output_dir)
print(f"Reading bag file: {bag_file}")
with rosbag.Bag(bag_file, 'r') as bag:
idx = 0
for topic, msg, t in bag.read_messages(topics=[topic]):
points = []
print(f"Reading message {idx} from topic: {topic} at time: {t}")
for point in pc2.read_points(msg, skip_nans=True):
points.append([point[0], point[1], point[2], point[3]])
points = np.array(points, dtype=np.float32)
print(f"Number of points: {points.shape[0]}")
# 生成输出bin文件路径
bin_file = os.path.join(output_dir, f'frame_{idx:06d}.bin')
print(f"Saving to bin file: {bin_file}")
points.tofile(bin_file)
idx += 1
print("Done")
# 单个bag文件路径
bag_file = '/media/happy406/046dcd53-ee66-4d3b-b556-5f9559acab84/0513/person_car.bag'
output_folder = '/media/happy406/046dcd53-ee66-4d3b-b556-5f9559acab84/0513/bin/output_frames/'
topic = '/rslidar_points'
# 将单个bag文件转换为多个bin文件
bag_to_bin(bag_file, output_folder, topic)
2、验证得到的bin文件是否有效,使用open3d来验证(pip install open3d),也是创建一个、check.py文件,将以下代码填入
import numpy as np
import open3d as o3d
def check_bin_file(bin_file):
# 读取bin文件
points = np.fromfile(bin_file, dtype=np.float32)
# 检查文件大小是否正确
if points.size % 4 != 0:
print("Error: File size is not correct. It should be a multiple of 4 floats.")
return
# 重新调整数组形状为(N, 4)
points = points.reshape((-1, 4))
# 打印前几个点检查格式
print("First few points:")
print(points[:5])
# 打印点的总数
print(f"Total points: {points.shape[0]}")
def visualize_bin_file(bin_file):
# 读取bin文件
points = np.fromfile(bin_file, dtype=np.float32).reshape((-1, 4))
print(f"Points loaded: {points.shape[0]}")
# 打印一些点的信息以供调试
print("First few points:", points[:5])
# 创建Open3D点云对象
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(points[:, :3])
# 打印点云信息供调试
print(f"Point cloud contains {len(pcd.points)} points")
# 可视化点云
o3d.visualization.draw_geometries([pcd])
# 单个bin文件路径
bin_file = '/media/happy406/046dcd53-ee66-4d3b-b556-5f9559acab84/0513/bin/output_frames/frame_000001.bin'
# 检查bin文件内容
check_bin_file(bin_file)
# 可视化点云数据
visualize_bin_file(bin_file)
结果会通过open3d打开刚才的bin文件,进行可视化,如果显示点云,则转换成功