在大型三维Numpy阵列中求局部极大值

2024-09-27 19:24:11 发布

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

我正在处理一些大体积的图像数据,这些数据以三维纽比阵列的形式出现。我将用两个小的一维阵列来解释我的任务。我有一个形象:

img = [5, 6, 70, 80, 3, 4, 80, 90]

还有一个经过分割和标记的图像:

^{pr2}$

labels中的每个数字代表img中的一个对象。两个数组的维数相同。所以在这个例子中,img中有两个对象:

[5,6,7080,3,4,8090]

我现在要做的是找到每个对象的最大值的位置,在本例中是3和{}。当前,我遍历所有标签,创建一个img版本,该版本只包含与当前标签对应的对象,并查找最大值:

for label in range(1, num_labels + 1):
    imgcp = np.copy(img)
    imgcp[labels != label] = 0
    max_pos = np.argmax(imgcp)
    max_coords = np.unravel_index(pos, imgcp.shape)

这种方法的一个问题是,在每个步骤中复制img会导致内存错误。我觉得内存管理应该可以防止这种情况发生,但是有没有一种内存效率更高、速度更快的方法来完成这项任务呢?在


Tags: 数据对象方法内存pos图像版本img
1条回答
网友
1楼 · 发布于 2024-09-27 19:24:11

下面是一个使用argpartition的方法。在

# small 2d example
>>> data = np.array([[0,1,4,0,0,2,1,0],[0,4,1,3,0,0,0,0]])
>>> segments = np.array([[0,1,1,0,0,2,2,0],[0,1,1,1,0,0,0,0]])
>>> 
# discard zeros
>>> nz = np.where(segments)
>>> segc = segments[nz]
>>> dac = data[nz]

# count object sizes
>>> cnts = np.bincount(segc)
>>> bnds = np.cumsum(cnts)
# use counts to partition into objects
>>> idx = segc.argpartition(bnds[1:-1])
>>> dai = dac[idx]
# find maxima per object
>>> mx = np.maximum.reduceat(dai, bnds[:-1])
# find their positions
>>> am, = np.where(dai==mx.repeat(cnts[1:]))
# translate positions back to coordinate space
>>> im = idx[am]
>>> am = *(n[im] for n in nz),
>>> 
>>> 
# result
# coordinates, note that there are more points than objects because
# the maximum 4 occurs twice in object 1
>>> am
(array([1, 0, 0]), array([1, 2, 5]))
# maxima
>>> data[am]
array([4, 4, 2])
# labels
>>> segments[am]
array([1, 1, 2])

相关问题 更多 >

    热门问题