将rgb颜色编码成一个float32浮点数

使用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类型的数据是以浮点数的方式存储的,不能直接移位操作.
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值