在三维数据处理中,点云数据的可视化是一个重要的步骤。本文将介绍如何使用Python的Matplotlib库来实现点云数据的绘制,以及如何计算并显示这些点云的最大外接边界框。
首先,我们需要导入必要的库:
import os
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
接下来,定义一个函数用于显示点云数据:
def display_point_cloud(data):
# 解决中文显示问题
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
fig = plt.figure()
ax = Axes3D(fig)
ax.set_title('点云')
ax.scatter3D(data[0], data[1], data[2], c='r', marker='.')
ax.set_xlabel('X轴')
ax.set_ylabel('Y轴')
ax.set_zlabel('Z轴')
plt.show()
然后,定义一个函数来绘制立方体,代表点云的最大边界框:
def plot_bounding_box(x, y, z, dx, dy, dz, color='blue'):
fig = plt.figure()
ax = Axes3D(fig)
xx = [x, x, x+dx, x+dx, x]
yy = [y, y+dy, y+dy, y, y]
kwargs = {'alpha': 1, 'color': color}
ax.plot3D(xx, yy, [z]*5, **kwargs)
ax.plot3D(xx, yy, [z+dz]*5, **kwargs)
ax.plot3D([x, x], [y, y], [z, z+dz], **kwargs)
ax.plot3D([x, x], [y+dy, y+dy], [z, z+dz], **kwargs)
ax.plot3D([x+dx, x+dx], [y+dy, y+dy], [z, z+dz], **kwargs)
ax.plot3D([x+dx, x+dx], [y, y], [z, z+dz], **kwargs)
plt.title('边界框')
plt.show()
最后,定义一个综合函数来同时显示点云和其边界框:
def plot_point_cloud_with_bbox(data, x, y, z, dx, dy, dz, color='blue'):
fig = plt.figure()
ax = Axes3D(fig)
ax.set_title('点云与边界框')
ax.scatter3D(data[0], data[1], data[2], c='r', marker='.')
ax.set_xlabel('X轴')
ax.set_ylabel('Y轴')
ax.set_zlabel('Z轴')
xx = [x, x, x+dx, x+dx, x]
yy = [y, y+dy, y+dy, y, y]
kwargs = {'alpha': 1, 'color': color}
ax.plot3D(xx, yy, [z]*5, **kwargs)
ax.plot3D(xx, yy, [z+dz]*5, **kwargs)
ax.plot3D([x, x], [y, y], [z, z+dz], **kwargs)
ax.plot3D([x, x], [y+dy, y+dy], [z, z+dz], **kwargs)
ax.plot3D([x+dx, x+dx], [y+dy, y+dy], [z, z+dz], **kwargs)
ax.plot3D([x+dx, x+dx], [y, y], [z, z+dz], **kwargs)
plt.show()
在主函数中,读取点云数据文件,并计算最小和最大的坐标值,以确定边界框的大小:
def main():
data = []
xlist = []
ylist = []
zlist = []
with open('./test_1_inliers.txt', 'r') as f:
lines = f.readlines()
for line in lines:
x, y, z = [float(i) for i in line.split(' ')]
xlist.append(x)
ylist.append(y)
zlist.append(z)
data.append(xlist)
data.append(ylist)
data.append(zlist)
xmin = min(xlist)
xmax = max(xlist)
ymin = min(ylist)
ymax = max(ylist)
zmin = min(zlist)
zmax = max(zlist)
dx = xmax - xmin
dy = ymax - ymin
dz = zmax - zmin
# 单独绘制点云或边界框
# plot_bounding_box(xmin, ymin, zmin, dx, dy, dz, color='blue')
# display_point_cloud(data)
# 绘制点云及边界框
plot_point_cloud_with_bbox(data, xmin, ymin, zmin, dx, dy, dz, color='blue')
if __name__ == '__main__':
main()
除了使用Matplotlib进行点云的可视化,还可以考虑使用Python-PCL库中的visualization模块,它提供了更多高级的点云处理功能。