NRRD space directions 中的采样间距与 none 非空间轴

10-10 5阅读

NRRD space directions 中的采样间距与 none 非空间轴

配图为AI生成概念示意图,不对应实际数据、测量比例或医学影像。

处理 NRRD 元数据时,把 space directions 中的向量全部归一化,会悄悄改变样本的位置。这里的向量描述沿数组某一轴前进一个索引时,在世界空间里产生的完整位移,长度本身也属于数据。

方向向量中已经包含间距

Teem 官方格式定义明确说明,space directions 同时表达方向与间距。在采用统一长度单位的三维直角坐标系中,向量的模长就是该轴相邻样本的距离。把 (2,0,0) 改成 (1,0,0),会把一步的实际位移缩短一半。

对零起点数组索引,计算方法是 world = origin + Σ index[i] × direction[i],求和只包含有空间方向的轴。官方库的数据结构说明把每个方向向量定义为索引到世界坐标变换的一个列向量;直接把这些向量当作矩阵的行使用,也可能得到错误结果。

none 要保留原来的轴位置

假设一份彩色体数据的数组轴依次是颜色分量和三个空间轴,尺寸为 (3,7,8,9)。方向字段可表示为 none (2,0,0) (0,3,0) (0,0,4)。第一项没有空间位移,但仍是数组中的一个有效轴,不能删掉后就把剩余方向与完整索引直接配对。

取原点 (10,20,30) 和索引 (2,3,4,5),正确位置为 (16,32,50);若擅自归一化,则变成 (13,24,35)。把颜色分量索引由二改成零,空间位置应保持不变。这里明确约定首轴为颜色;仅凭 none 本身不能推断它一定是 RGB,还要结合 kinds 或应用上下文。

完整 Python 示例

下面处理已解析的元数据,使用 Python 的 None 表示字段中的 none。两段代码依次保存为 test.py,执行 python3 test.py -v。它只计算三维世界空间中的已知样本位置,不读取 NRRD 头部、像素载荷或压缩数据。

函数检查每轴字段数量、正整数尺寸、全部轴的索引范围,以及三分量向量和计算结果的有限性。非空间轴也要检查索引边界。示例支持一至十六个数组轴,拒绝零方向向量和未知坐标,是为了限定可直接计算的输入;这些检查不构成完整的 NRRD 文件验证。

"""3D world coordinates from already-parsed NRRD metadata.
This is not a complete NRRD file reader. Run: python3 test.py -v
"""
import math
import unittest


def vector3(value):
    if not isinstance(value, (list, tuple)) or len(value) != 3:
        raise ValueError("expected a three-component vector")
    if any(type(x) not in (int, float) for x in value):
        raise ValueError("vector components must be numbers")
    try:
        result = tuple(float(x) for x in value)
    except OverflowError as exc:
        raise ValueError("vector component overflow") from exc
    if not all(math.isfinite(x) for x in result):
        raise ValueError("vector components must be finite")
    return result


def index_to_world(index, sizes, origin, directions):
    """Use original NRRD axis order; represent 'none' with Python None."""
    if any(not isinstance(x, (tuple, list)) for x in (index, sizes, directions)):
        raise ValueError("index, sizes, and directions must be sequences")
    if not 1 <= len(sizes) <= 16:
        raise ValueError("this example supports 1..16 array axes")
    if len(index) != len(sizes) or len(directions) != len(sizes):
        raise ValueError("per-axis field lengths differ")
    origin = vector3(origin)
    vectors = []
    for position, size, direction in zip(index, sizes, directions):
        if type(size) is not int or size <= 0:
            raise ValueError("axis sizes must be positive integers")
        if type(position) is not int or not 0 <= position < size:
            raise ValueError("index is outside the axis")
        if direction is None:
            vectors.append(None)
            continue
        direction = vector3(direction)
        if not any(direction):
            raise ValueError("zero direction is outside this example&#x27;s scope")
        vectors.append(direction)
    try:
        world = tuple(math.fsum([origin[k]] + [position * direction[k]
                      for position, direction in zip(index, vectors)
                      if direction is not None]) for k in range(3))
    except (OverflowError, ValueError) as exc:
        raise ValueError("coordinate arithmetic overflow") from exc
    if not all(math.isfinite(x) for x in world):
        raise ValueError("coordinate arithmetic overflow")
    return world

测试归一化错误与轴重排

测试不仅验证正常位置,还显式证明归一化后的错误结果。旋转、负方向和非正交轴分别有用例,避免只在与坐标轴平行的数据上验证。重排测试同时变换索引、尺寸和方向列表,确认它们仍然逐轴对应。

class NrrdGeometryTests(unittest.TestCase):
    def setUp(self):
        self.sizes = (3, 7, 8, 9)
        self.origin = (10, 20, 30)
        self.directions = (None, (2, 0, 0), (0, 3, 0), (0, 0, 4))

    def test_scaled_axes(self):
        result = index_to_world((2, 3, 4, 5), self.sizes, self.origin, self.directions)
        self.assertEqual(result, (16.0, 32.0, 50.0))

    def test_none_axis_does_not_move_position(self):
        for channel in range(3):
            with self.subTest(channel=channel):
                self.assertEqual(index_to_world((channel, 3, 4, 5), self.sizes,
                                               self.origin, self.directions),
                                 (16.0, 32.0, 50.0))

    def test_zero_index_is_sample_center_origin(self):
        self.assertEqual(index_to_world((0, 0, 0, 0), self.sizes,
                                       self.origin, self.directions), self.origin)

    def test_normalizing_loses_spacing(self):
        unit = tuple(None if d is None else tuple(x / math.hypot(*d) for x in d)
                     for d in self.directions)
        wrong = index_to_world((2, 3, 4, 5), self.sizes, self.origin, unit)
        self.assertEqual(wrong, (13.0, 24.0, 35.0))
        self.assertNotEqual(wrong, (16.0, 32.0, 50.0))

    def test_rotated_and_negative_directions(self):
        directions = (None, (0, 2, 0), (-3, 0, 0), (0, 0, 4))
        self.assertEqual(index_to_world((1, 2, 3, 4), self.sizes,
                                       (10, -5, 7), directions), (1.0, -1.0, 23.0))

    def test_oblique_axes_need_not_be_orthogonal(self):
        self.assertEqual(index_to_world((2, 3, 4), (5, 5, 5), (0, 0, 0),
                                       ((1, 0, 0), (1, 1, 0), (0, 0, 2))),
                         (5.0, 3.0, 8.0))

    def test_permuted_metadata_and_indices(self):
        order = (3, 0, 2, 1)
        index = (2, 3, 4, 5)
        self.assertEqual(index_to_world(tuple(index[i] for i in order),
                                       tuple(self.sizes[i] for i in order), self.origin,
                                       tuple(self.directions[i] for i in order)),
                         (16.0, 32.0, 50.0))

    def test_axis_lengths_and_vector_shapes(self):
        with self.assertRaisesRegex(ValueError, "lengths"):
            index_to_world((1, 2, 3), self.sizes, self.origin, self.directions)
        with self.assertRaisesRegex(ValueError, "lengths"):
            index_to_world((1, 2, 3, 4), self.sizes, self.origin, self.directions[1:])
        for vector in ((1, 2), (1, 2, 3, 4), None):
            with self.subTest(vector=vector), self.assertRaises(ValueError):
                index_to_world((0,), (1,), vector, ((1, 0, 0),))

    def test_bounds_include_none_axis(self):
        for index in ((3, 0, 0, 0), (0, 7, 0, 0), (0, -1, 0, 0), (True, 0, 0, 0)):
            with self.subTest(index=index), self.assertRaises(ValueError):
                index_to_world(index, self.sizes, self.origin, self.directions)

    def test_invalid_sizes_and_axis_count(self):
        for size in (0, -1, True, 2.5):
            with self.subTest(size=size), self.assertRaises(ValueError):
                index_to_world((0,), (size,), (0, 0, 0), ((1, 0, 0),))
        with self.assertRaises(ValueError):
            index_to_world((), (), (0, 0, 0), ())
        with self.assertRaises(ValueError):
            index_to_world((0,) * 17, (1,) * 17, (0, 0, 0), (None,) * 17)

    def test_invalid_directions(self):
        for direction in ((0, 0, 0), (1, 2), (math.nan, 0, 0), (math.inf, 0, 0),
                          (True, 0, 0), ("1", 0, 0), (10 ** 1000, 0, 0)):
            with self.subTest(direction=direction), self.assertRaises(ValueError):
                index_to_world((0,), (1,), (0, 0, 0), (direction,))

    def test_arithmetic_overflow(self):
        with self.assertRaisesRegex(ValueError, "overflow"):
            index_to_world((3,), (4,), (0, 0, 0), ((1e308, 0, 0),))


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

实际运行与接入边界

上述代码在 Python 3.12.14 下实际执行,十二项测试全部通过,包含多组非法输入子用例;从最终 HTML 提取代码再次运行也通过。源代码仅使用普通 ASCII 空格和标准库。

NRRD 的每轴信息按最快变化轴到最慢变化轴排列,接入数组库时要核对该库的索引约定。如果需要重排轴,相关元数据与索引应一起调整。space origin 表示第一个样本中心的位置,零索引应直接回到原点,不要额外补半个体素。这个定义也见于官方库说明。

当方向或原点信息缺失时,不应悄悄编造单位间距或零原点。若确有应用层约定,应明确记录后再计算。本文只演示文件几何关系,不涉及医学判读;样本值本身的向量坐标变换也不在这个位置计算函数的范围内。

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