简体   繁体   English

3D numpy 数组中的两个非零元素是否“连接”?

[英]Are two non-zero elements in a 3D numpy array “connected”?

Viewing a 3D numpy array as representing a 3D space, two array indices A and B are "connected" if there exists a Path from A to B, where a Path is a list of array indices where every adjacent element pair Path[i] and Path[i+1] are (1) indices to non-zero elements in the input array and (2) "next" to each other, np.max(np.abs(Path[i] - Path[i+1])) <= 1.将 3D 空间视为 3D 空间的 3D numpy 数组,如果存在从 A 到 B 的每个相邻元素的路径,则两个数组索引 A 和 B 是“连接的”,其中 Path[i] 是数组索引的列表Path[i+1] 是 (1) 输入数组中非零元素的索引和 (2) “下一个”,np.max(np.abs(Path[i] - Path[i+1] )) <= 1。

Given an initial index A, I'd like to generate the list A_Connected which is the list of all array indices which are "connected" to A.给定一个初始索引 A,我想生成列表 A_Connected,它是所有“连接”到 A 的数组索引的列表。

My slow method would be:我的慢方法是:

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

You need to look at the problem under a completely different angle.你需要从一个完全不同的角度来看待这个问题。 It is a graph problem for which you need a transition matrix.这是一个需要转换矩阵的图形问题。

  • for each element of your array, you should identify its immediate connected neighbours对于数组的每个元素,您应该确定其直接连接的邻居

  • the result of this should be stored in a 2d NxN array where N is the total number of elements in you 3d array, this is the transition matrix T结果应存储在 2d NxN 数组中,其中 N 是 3d 数组中的元素总数,这是转换矩阵 T

  • your departure point is then a vector V of length N with N-1 zeros and one 1然后,您的出发点是长度为 N 的向量 V,其中 N-1 个零和一个 1

  • compute T^k V and increase T to find all connected points that are k steps away from V计算 T^k V 并增加 T 以找到距离 V 为 k 步的所有连接点

This is only a guideline, you will find details here .这只是一个指南,您将在此处找到详细信息。

Python coding is not very difficult. Python编码不是很困难。 You can use the fact that T is symmetric with 1's in the diagonal to fasten the process.您可以使用 T 与对角线中的 1 对称的事实来加快该过程。

Hope that it helps.希望它有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM