如何在 Python 中以 RGBE 格式快速读取 hdr 图像?

问题描述

我想知道如何通过在 Python 中快速高效地获取 RGBE 格式的像素值来读取 HDR 图像 (.hdr)。

这些是我尝试过的:

    import imageio
    img = imageio.imread(hdr_path,format="HDR-FI")

或者:

    import cv2
    img = cv2.imread(hdr_path,flags=cv2.IMREAD_ANYDEPTH)

这会读取图像,但以 RGB 格式给出值。

如何在不改变 RGB 值的情况下获得第 4 个通道,即每个像素的“E”通道? 我更喜欢只涉及 imageio 的解决方案,因为我只能使用该模块。

解决方法

如果您更喜欢 RGBE 表示而不是浮点表示,您可以在两者之间进行转换

def float_to_rgbe(image,*,channel_axis=-1):

    # ensure channel-last
    image = np.moveaxis(image,channel_axis,-1)

    max_float = np.max(image,axis=-1)
    
    scale,exponent = np.frexp(max_float)
    scale *= 256.0/max_float

    image_rgbe = np.empty((*image.shape[:-1],4)
    image_rgbe[...,:3] = image * scale
    image_rgbe[...,-1] = exponent + 128

    image_rgbe[scale < 1e-32,:] = 0
    
    # restore original axis order
    image_rgbe = np.moveaxis(image_rgbe,-1,channel_axis)

    return image_rgbe

(注意:这是基于 RGBE 参考实现(found here),如果确实是瓶颈,可以进一步优化。)

在您的评论中,您提到“如果我手动解析 numpy 数组并将通道拆分为 E 通道,则需要太多时间...”,但是如果没有看到代码。上面是O(height*width),对于像素级的图像处理方法来说,这似乎是合理的。