python - 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
解决方案
你需要从一个完全不同的角度来看待这个问题。这是一个需要转换矩阵的图形问题。
对于数组的每个元素,您应该确定其直接连接的邻居
结果应该存储在 2d NxN 数组中,其中 N 是 3d 数组中元素的总数,这是转换矩阵 T
然后,您的出发点是长度为 N 的向量 V,其中 N-1 个零和一个 1
计算 T^k V 并增加 T 以找到距离 V 为 k 步的所有连接点
这只是一个指南,您可以在此处找到详细信息。
Python编码不是很困难。您可以使用 T 与对角线中的 1 对称的事实来加快该过程。
希望它有所帮助。
推荐阅读
- node.js - Nodejs Mongoose - 检查数组对象值是否存在,如果不存在则将新对象添加到数组中
- android - 如何在android studio中读取输出张量(tflite)
- r - 如何使用 R 中的某些公式将季度数据分解为月度数据?
- python - 根据值对列表进行排序,如果相同的值使用索引对其进行排序
- c++ - volatile 和 mutex 是否确保 C++ 中的内存排序?
- java - “选择新构造函数”查询返回 java.lang.Object 而不是构造函数类的实例
- ruby - 奥丁计划:关于棋盘颜色的问题
- swift - 使用信号量来限制最新的 DispatchQueue
- python - 您可以将字符串中的字符添加到列表中吗?
- python-3.x - 我想比较两个字符串,以便创建一个在 string1 中找到但在第二个中没有的缺失元素的新字符串