使用python的pypcd包读写pcd文件,需要将[r, g, b]三通道颜色转换成一个float32数和与之对应的逆变换,分别称作编码器和解码器
def encode_rgb_for_pcl(rgb):
""" Encode bit-packed RGB for use with PCL.
:param rgb: Nx3 uint8 array with RGB values.
:rtype: Nx1 float32 array with bit-packed RGB, for PCL.
"""
assert(rgb.dtype == np.uint8)
assert(rgb.ndim == 2)
assert(rgb.shape[1] == 3)
rgb = rgb.astype(np.uint32)
rgb = np.array((rgb[:, 0] << 16) | (rgb[:, 1] << 8) | (rgb[:, 2] << 0),
dtype=np.uint32)
rgb.dtype = np.float32
return rgb
def decode_rgb_from_pcl(rgb):
""" Decode the bit-packed RGBs used by PCL.
:param rgb: An Nx1 array.
:rtype: Nx3 uint8 array with one column per color.
"""
rgb = rgb.copy()
rgb.dtype = np.uint32
r = np.asarray((rgb >> 16) & 0xFF, dtype=np.uint8)
g = np.asarray((rgb >> 8) & 0xFF, dtype=np.uint8)
b = np.asarray(rgb & 0xFF, dtype=np.uint8)
rgb_arr = np.zeros((len(rgb), 3), dtype=np.uint8)
rgb_arr[:, 0] = r
rgb_arr[:, 1] = g
rgb_arr[:, 2] = b
return rgb_arr
Tips:
- encoder中所有的像素值用uint8类型,因为opencv中是这么做的,表示0-255的数据这就足够了,为了用统一的标准.
- encoder中进行移位操作前,将数据类型转换成uint32,因为需要对r左移16位,g左移8位,uint8的8bit不够用了.为什么不直接用float32或者float64呢?因为float和double类型的数据是以浮点数的方式存储的,不能直接移位操作.