我正在处理一个大数组(3000 x 3000(,我使用它scipy.ndimage.label
。返回的是 3403 个标签和标记的数组。我想知道这些标签的索引,例如对于标签 1,我应该知道标签数组中的行和列。 所以基本上是这样的
a[0] = array([[1, 1, 0, 0],
[1, 1, 0, 2],
[0, 0, 0, 2],
[3, 3, 0, 0]])
indices = [np.where(a[0]==t+1) for t in range(a[1])] #where a[1] = 3 is number of labels.
print indices
[(array([0, 0, 1, 1]), array([0, 1, 0, 1])), (array([1, 2]), array([3, 3])), (array([3, 3]), array([0, 1]))]
我想像上面一样为所有 3403 个标签创建一个索引列表。上面的方法似乎很慢。我尝试使用发电机,看起来没有改进。
有什么有效的方法吗?
提高效率的想法是,一旦进入循环,就尽量减少工作量。矢量化方法是不可能的,因为每个标签的元素数量是可变的。因此,考虑到这些因素,这里有一个解决方案——
a_flattened = a[0].ravel()
sidx = np.argsort(a_flattened)
afs = a_flattened[sidx]
cut_idx = np.r_[0,np.flatnonzero(afs[1:] != afs[:-1])+1,a_flattened.size]
row, col = np.unravel_index(sidx, a[0].shape)
row_indices = [row[i:j] for i,j in zip(cut_idx[:-1],cut_idx[1:])]
col_indices = [col[i:j] for i,j in zip(cut_idx[:-1],cut_idx[1:])]
样本输入、输出 -
In [59]: a[0]
Out[59]:
array([[1, 1, 0, 0],
[1, 1, 0, 2],
[0, 0, 0, 2],
[3, 3, 0, 0]])
In [60]: a[1]
Out[60]: 3
In [62]: row_indices # row indices
Out[62]:
[array([0, 0, 1, 2, 2, 2, 3, 3]), # for label-0
array([0, 0, 1, 1]), # for label-1
array([1, 2]), # for label-2
array([3, 3])] # for label-3
In [63]: col_indices # column indices
Out[63]:
[array([2, 3, 2, 0, 1, 2, 2, 3]), # for label-0
array([0, 1, 0, 1]), # for label-1
array([3, 3]), # for label-2
array([0, 1])] # for label-3
row_indices
和col_indices
的第一个元素是预期的输出。每个组中的前一组表示0-th
区域,因此您可能希望跳过这些区域。