首页 > 解决方案 > 3D numpy 数组中的两个非零元素是否“连接”?

问题描述

将 3D numpy 数组视为表示 3D 空间,如果存在从 A 到 B 的路径,则两个数组索引 A 和 B 是“连接的”,其中 Path 是数组索引列表,其中每个相邻元素对 Path[i] 和Path[i+1] 是 (1) 输入数组中非零元素的索引和 (2) “下一个”,np.max(np.abs(Path[i] - Path[i+1] )) <= 1。

给定一个初始索引 A,我想生成列表 A_Connected,它是所有“连接”到 A 的数组索引的列表。

我的慢方法是:

def find_connected_list(array, index, connected_list):
   connected_list.append(index)

   for x in range(index[0]-1, index[0]+2):
      for y in range(index[1]-1, index[1]+2):
         for z in range(index[2]-1, index[2]+2):
            if x>= 0 and x < array.shape[0] and y >= 0 and y < array.shape[1] and z >= 0 and z < array.shape[2] and array[x,y,z] > 0 and not [x,y,z] in connected_list:
               connected_list = find_connected_list(array, [x,y,z], connected_list)

   return connected_list

标签: pythonnumpy

解决方案


你需要从一个完全不同的角度来看待这个问题。这是一个需要转换矩阵的图形问题。

  • 对于数组的每个元素,您应该确定其直接连接的邻居

  • 结果应该存储在 2d NxN 数组中,其中 N 是 3d 数组中元素的总数,这是转换矩阵 T

  • 然后,您的出发点是长度为 N 的向量 V,其中 N-1 个零和一个 1

  • 计算 T^k V 并增加 T 以找到距离 V 为 k 步的所有连接点

这只是一个指南,您可以在此处找到详细信息。

Python编码不是很困难。您可以使用 T 与对角线中的 1 对称的事实来加快该过程。

希望它有所帮助。


推荐阅读