在三维numpy数组中查找区域的中心坐标

2024-05-15 14:30:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个大的三维数组(10000,3,3)。其中我想找到每个区域的中心坐标(具有相同编号的簇)。每个区域可以有2个或4个子阵列。在

数组的一个子集是:

largearray= array([[[1, 0, 0],
    [0, 0, 2],
    [3, 0, 2]],

   [[0, 0, 4],
    [0, 0, 4],
    [0, 0, 4]],

   [[5, 0, 0],
    [5, 0, 6],
    [0, 6, 6]],

   [[7, 0, 8],
    [0, 0, 0],
    [9, 0,10]]])

我想要的输出是子阵列的位置和代表中心的x和y坐标:

^{pr2}$

我对其他的输出很开放,但是像这样的东西会很棒的!在

提前谢谢!在


Tags: 区域代表数组中心array子集编号pr2
3条回答

你在找这个吗?在

n_clusters = 10
for i in range(1, n_clusters + 1):
    matches = np.transpose((largearray == i).nonzero())
    print "The center of cluster {} is at {}".format(i, np.mean(matches, axis=0))
^{pr2}$

您可能还想查看处理与此相关的问题的^{}包。[免责声明:我是合著者]。它应该比numpy-indexed(另一个答案中提到的包)快,因为它使用bincount,而不是{}和{}。在

但是,这里的任务非常简单,可以直接使用bincount

s0, s1, s2 = a.shape

group_counts = np.bincount(a.ravel())

idx = np.broadcast_to(np.arange(s0).reshape([s0, 1, 1]), [s0,s1,s2])
group_sum_0 = np.bincount(a.ravel(), idx.ravel()) 

idx = np.broadcast_to(np.arange(s1).reshape([1, s1, 1]), [s0,s1,s2])
group_sum_1 = np.bincount(a.ravel(), idx.ravel()) 

idx = np.broadcast_to(np.arange(s2).reshape([1, 1, s2]), [s0,s1,s2])
group_sum_2 = np.bincount(a.ravel(), idx.ravel()) 

group_mean = np.vstack((group_sum_0, group_sum_1, group_sum_2)) / group_counts

group_mean.T[1:] # this is the output you show in the question

或者,如果你想“作弊”,你可以使用scipy的ndimage.measurements中的一个函数。在

使用numpy_indexed包中的功能(免责声明:我是其作者),可以构造一个完全矢量化的解决方案(即,没有for循环):

import numpy_indexed as npi
idx = np.indices(largearray.shape).reshape(largearray.ndim, largearray.size)
label, mean = npi.group_by(largearray, axis=None).mean(idx, axis=1)

对于大的投入,这应该会更有效率。在

请注意,如果标签在每个子阵列中不是唯一的(它们在您的示例中似乎是,但这没有明确说明),但是您仍然希望只取每个子阵列的平均值,您可以简单地写下:

^{pr2}$

也就是说,通过子数组索引和标签的唯一元组进行分组。在

相关问题 更多 >