RGBE 共享指数如何还原 HDR 数值与解释量化误差

10-10 6阅读

RGBE 共享指数如何还原 HDR 数值与解释量化误差

配图为AI生成的概念示意图,不是实际软件截图或测量图。

RGBE 用四个字节保存三个线性颜色分量:三个八位尾数,以及一个共享指数。理解它的关键,是最大通道决定三个通道共同使用的量化步长。下面只实现单像素数值转换,不读取 HDR 文件头、扫描行编码或曝光元数据。

指数偏置与尾数缩放

Radiance 官方格式说明给出了四字节布局。本文的编码公式核对 项目 color.c 中的 setcolr,解码公式核对 color.h 的 COLXS、cx2real 与 colr_color。本次读取的 color.c 标注版本为二点四二,使用系数 256.0;早期说明附带的旧代码使用 255.9999,不要混用两版结果。

对非黑色像素,先用 frexp(max(R,G,B)) 取得指数 e,使最大分量写成 m × 2^e,其中 0.5 ≤ m < 1。存储的指数为 E = e + 128,每个尾数为 q = floor(c × 2^(8-e))。

因此该像素的步长为 Δ = 2^(E-136)。一百三十六来自指数偏置一百二十八与八位尾数缩放之和。参考解码器采用量化区间中点,输出 (q + 0.5) × Δ。当 E = 0 时直接返回黑色,不进入普通指数计算。

为何往返后不是原来的数值

输入 (1, 0.5, 0.25) 会编码成 (128, 64, 32, 129)。按上述中点策略解码,得到 (1.00390625, 0.50390625, 0.25390625)。这个差值来自有损量化,不能用浮点数逐项完全相等作为往返测试。

这个指数是每个像素单独选择的。写编码器时,应先求同一像素的最大分量,再统一缩放三个通道;如果分别求指数,却只保存其中一个,解码结果就会错位。最大分量跨过二次幂边界时,指数上升,步长也随之翻倍,所以接近边界的输入尤其值得单独测试。

更明显的例子是 (1024, 1, 0):步长已经变成八,尾数为 (128, 0, 0),中点重建结果为 (1028, 4, 4)。弱通道与零通道都会受到共同步长影响。共享指数扩大了可表示的亮度范围,却没有给每个通道独立的八位相对精度。

完整 Python 实现

将两段代码依次保存为 test.py,执行 python3 test.py -v,无需安装依赖。这里严格接收有限、非负的数值;拒绝 NaN、无穷、负数及指数溢出。源代码中的最大通道不超过 1e-32 时写黑色的策略也被保留,这是编码实现的阈值,并非格式只能解码到这个下限。

"""Single-pixel RGBE conversion. Run: python3 test.py -v"""
import math
import unittest


def encode_rgbe(rgb):
    """Encode three finite nonnegative linear values, not an HDR file."""
    if not isinstance(rgb, (tuple, list)) or len(rgb) != 3:
        raise ValueError("RGB must contain exactly three values")
    values = []
    for item in rgb:
        if type(item) not in (int, float):
            raise TypeError("RGB values must be int or float")
        try:
            value = float(item)
        except OverflowError as exc:
            raise ValueError("RGB value is too large") from exc
        if not math.isfinite(value) or value < 0:
            raise ValueError("RGB values must be finite and nonnegative")
        values.append(value)
    peak = max(values)
    # Match Radiance setcolr&#x27;s practical black threshold.
    if peak <= 1e-32:
        return bytes(4)
    _, exponent = math.frexp(peak)
    stored_exponent = exponent + 128
    if not 1 <= stored_exponent <= 255:
        raise ValueError("RGBE exponent is out of range")
    mantissas = [int(math.ldexp(v, 8 - exponent)) for v in values]
    if any(not 0 <= m <= 255 for m in mantissas):
        raise ValueError("RGBE mantissa is out of range")
    return bytes(mantissas + [stored_exponent])


def decode_rgbe(pixel):
    """Radiance midpoint reconstruction; return three linear values."""
    if not isinstance(pixel, bytes):
        raise TypeError("pixel must be bytes")
    if len(pixel) != 4:
        raise ValueError("one RGBE pixel requires exactly four bytes")
    r, g, b, exponent = pixel
    if exponent == 0:
        return (0.0, 0.0, 0.0)
    return tuple(math.ldexp(m + 0.5, exponent - 136) for m in (r, g, b))

把边界写进测试

测试包含二次幂前后的指数切换、黑色阈值两侧、最高可用指数、错误长度,以及所有二百五十五个非零指数的代表尾数。误差测试仅针对未被归黑、未溢出的输入,检查每个分量的绝对误差不超过半个共同步长。

class RgbeTests(unittest.TestCase):
    def test_known_encoding(self):
        self.assertEqual(encode_rgbe((1, 0.5, 0.25)), bytes((128, 64, 32, 129)))

    def test_midpoint_reconstruction(self):
        self.assertEqual(decode_rgbe(bytes((128, 64, 32, 129))),
                         (1.00390625, 0.50390625, 0.25390625))

    def test_zero_exponent(self):
        self.assertEqual(decode_rgbe(bytes(4)), (0.0, 0.0, 0.0))
        self.assertEqual(decode_rgbe(bytes((255, 99, 1, 0))), (0.0, 0.0, 0.0))

    def test_black_threshold(self):
        for peak in (0.0, 1e-40, math.nextafter(1e-32, 0.0), 1e-32):
            with self.subTest(peak=peak):
                self.assertEqual(encode_rgbe((peak, 0, 0)), bytes(4))
        self.assertNotEqual(encode_rgbe((math.nextafter(1e-32, math.inf), 0, 0)), bytes(4))

    def test_power_of_two_boundary(self):
        self.assertEqual(encode_rgbe((math.nextafter(1.0, 0.0), 0, 0)),
                         bytes((255, 0, 0, 128)))
        self.assertEqual(encode_rgbe((1.0, 0, 0)), bytes((128, 0, 0, 129)))

    def test_weak_channel_precision(self):
        pixel = encode_rgbe((1024, 1, 0))
        self.assertEqual(pixel, bytes((128, 0, 0, 139)))
        self.assertEqual(decode_rgbe(pixel), (1028.0, 4.0, 4.0))

    def test_nonfinite_and_negative_input(self):
        for value in (-1, math.nan, math.inf, -math.inf):
            with self.subTest(value=value), self.assertRaises(ValueError):
                encode_rgbe((value, 0, 0))

    def test_invalid_rgb_shape_and_type(self):
        for rgb in ((), (1, 2), (1, 2, 3, 4), "123", None):
            with self.subTest(rgb=rgb), self.assertRaises(ValueError):
                encode_rgbe(rgb)
        for value in (True, "1", None, 1j):
            with self.subTest(value=value), self.assertRaises(TypeError):
                encode_rgbe((value, 0, 0))

    def test_upper_exponent_boundary(self):
        largest = math.nextafter(math.ldexp(1.0, 127), 0.0)
        self.assertEqual(encode_rgbe((largest, 0, 0)), bytes((255, 0, 0, 255)))
        for value in (math.ldexp(1.0, 127), 1e300, 10 ** 1000):
            with self.subTest(value=value), self.assertRaises(ValueError):
                encode_rgbe((value, 0, 0))

    def test_invalid_pixel(self):
        for pixel in (b"", b"abc", b"abcde"):
            with self.subTest(pixel=pixel), self.assertRaises(ValueError):
                decode_rgbe(pixel)
        with self.assertRaises(TypeError):
            decode_rgbe([128, 64, 32, 129])

    def test_all_nonzero_exponents(self):
        for exponent in range(1, 256):
            for m in (0, 1, 127, 128, 255):
                with self.subTest(exponent=exponent, mantissa=m):
                    value = decode_rgbe(bytes((m, m, m, exponent)))[0]
                    self.assertTrue(math.isfinite(value) and value > 0)
                    self.assertEqual(value, (m + 0.5) * 2.0 ** (exponent - 136))

    def test_quantization_error_bound(self):
        for exponent in (-100, -20, 0, 20, 100, 127):
            for fraction in (0.5, 0.75, 0.999):
                peak = math.ldexp(fraction, exponent)
                rgb = (peak, peak / 17, 0.0)
                pixel = encode_rgbe(rgb)
                reconstructed = decode_rgbe(pixel)
                step = math.ldexp(1.0, pixel[3] - 136)
                with self.subTest(exponent=exponent, fraction=fraction):
                    for original, decoded in zip(rgb, reconstructed):
                        self.assertLessEqual(abs(original - decoded), step / 2)


if __name__ == "__main__":
    unittest.main()

运行结果与使用范围

上述完整文件在 Python 3.12.14 下实际执行,输出 Ran 12 tests 与 OK,其中包含多组子用例。也从文章 HTML 提取代码后重新运行,结果相同。

实际接入时,输入应当已经处于所需的线性颜色空间;编码函数不执行 sRGB 解码、色域转换或色调映射。本文明确采用 Radiance 的中点重建约定,若其他库省略半步长,比较前应先统一约定。RGBE 往返不是无损操作,弱通道的误差应结合最大通道和步长判断。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。