点云学习笔记7——python pcl将点云数据转换成俯视图(鸟瞰图)

 

环境安装

可以参考我另外一篇文章:

点云学习笔记3——点云库(PCL)安装与测试教程

点云数据 代码

import numpy as np
import pcl

#下面的代码将感兴趣的矩形设置为在原点的两侧,跨度为10米,并在其前面20米处。
side_range=(-20, 20)     # left-most to right-most
fwd_range=(-20, 20)       # back-most to forward-most

print(side_range)
print(fwd_range)

pt = pcl.load('PointClouds/0120.pcd')

shape = pt.to_array().transpose()
# 现在shape是numpy.ndarray


x = shape[0]
y = shape[1]
z = shape[2]

# EXTRACT THE POINTS FOR EACH AXIS
# x_points = x[:, 0]
# y_points = y[:, 1]
# z_points = z[:, 2]

x_points =  shape[0]
y_points =  shape[1]
z_points =  shape[2]
print(x_points)
# FILTER - To return only indices of points within desired cube
# Three filters for: Front-to-back, side-to-side, and height ranges
# Note left side is positive y axis in LIDAR coordinates

#创建一个过滤器,仅保留实际位于指定的矩形内的点。

f_filt = np.logical_and((x_points > fwd_range[0]), (x_points < fwd_range[1]))
s_filt = np.logical_and((y_points > -side_range[1]), (y_points < -side_range[0]))
filter = np.logical_and(f_filt, s_filt)
indices = np.argwhere(filter).flatten()

# KEEPERS
x_points = x_points[indices]
y_points = y_points[indices]
z_points = z_points[indices]


#将点位置映射到像素位置
res = 0.05
# CONVERT TO PIXEL POSITION VALUES - Based on resolution
x_img = (-y_points / res).astype(np.int32)  # x axis is -y in LIDAR
y_img = (-x_points / res).astype(np.int32)  # y axis is -x in LIDAR

#平移原点
#x和y值仍有负数,还不能投影到图像上,因此还需要平移数据,使得(0,0)位置的数据最小。

# SHIFT PIXELS TO HAVE MINIMUM BE (0,0)
# floor and ceil used to prevent anything being rounded to below 0 after shift
x_img -= int(np.floor(side_range[0] / res))
y_img += int(np.ceil(fwd_range[1] / res))


height_range = (-2, 0.5)  # bottom-most to upper-most

# CLIP HEIGHT VALUES - to between min and max heights
pixel_values = np.clip(a = z_points,
                           a_min=height_range[0],
                           a_max=height_range[1])


def scale_to_255(a, min, max, dtype=np.uint8):
    """ Scales an array of values from specified min, max range to 0-255
        Optionally specify the data type of the output (default is uint8)
    """
    return (((a - min) / float(max - min)) * 255).astype(dtype)

# RESCALE THE HEIGHT VALUES - to be between the range 0-255
pixel_values  = scale_to_255(pixel_values, min=height_range[0], max=height_range[1])


# INITIALIZE EMPTY ARRAY - of the dimensions we want
x_max = 1+int((side_range[1] - side_range[0])/res)
y_max = 1+int((fwd_range[1] - fwd_range[0])/res)
im = np.zeros([y_max, x_max], dtype=np.uint8)

# FILL PIXEL VALUES IN IMAGE ARRAY
im[y_img, x_img] = pixel_values

# CONVERT FROM NUMPY ARRAY TO A PIL IMAGE
from PIL import Image
im2 = Image.fromarray(im)
im2.show()

import matplotlib.pyplot as plt
plt.imshow(im, cmap="spectral", vmin=0, vmax=255)
plt.show()
效果图

点云学习笔记7——python pcl将点云数据转换成俯视图(鸟瞰图)_python

点云学习笔记7——python pcl将点云数据转换成俯视图(鸟瞰图)_原力计划_02