有没有一种有效的方法可以使用一个数组的内容作为查找表来确定第二个数组的内容?

问题描述 投票:0回答:1

我有一系列点:

centers = array([0,0,0,0],
                [0,1,0,0],  
                [0,0,0,1],    
                [1,0,0,0])

使用 scikit.ndimage.distance_transform_edt(),最接近每个背景元素的点的索引在单独的数组中返回:

indexes = array([[1,1],[1,1],[1,1],[3,2]],
                [[1,1],[1,1],[1,1],[3,2]],
                [[0,3],[1,1],[3,2],[3,2]],
                [[0,3],[0,3],[0,3],[3,2]])

然后我将原始数组标记为具有唯一值:

labeled_centers = array([0,0,0,0],
                        [0,2,0,0],
                        [0,0,0,3],
                        [4,0,0,0])

我的问题是,使用索引数组创建新数组的最有效方法是什么,其中每个点都标有最近中心点的标签?

labeled_image = array([2,2,2,1,1],
                      [2,2,2,3,1],
                      [4,2,3,3,3],
                      [4,4,4,3,3])

到目前为止,我已经通过循环数组中的每个值达到了我想要的结果,如下所示:

classed = np.zeros_like(centers)

for x in range(classed.shape[0]):
    for y in range(classed.shape[1]):
        classed[x,y] = labeled_centers[indexes[0,x,y],indexes[1,x,y]]

但是,虽然我的示例是一个小数组,但我的实际用例将涉及数百万甚至数十亿个数据点的数组,因此我试图避免编写每个值的“for”循环。有没有更有效的方法来达到相同的结果?

python numpy numpy-ndarray scikit-image
1个回答
0
投票

将代码更改为实际有效的代码:

import numpy as np

centers = np.array([[0,0,0,0],
                [0,1,0,0],  
                [0,0,0,1],    
                [1,0,0,0]])

indexes = np.array([[[1,1],[1,1],[1,1],[3,2]],
                [[1,1],[1,1],[1,1],[3,2]],
                [[0,3],[1,1],[3,2],[3,2]],
                [[0,3],[0,3],[0,3],[3,2]]])

labeled_centers = np.array([[0,0,0,0],
                        [0,2,0,0],
                        [0,0,0,3],
                        [4,0,0,0]])

classed = np.zeros_like(centers)

for x in range(classed.shape[0]):
    for y in range(classed.shape[1]):
        classed[x,y] = labeled_centers[indexes[x,y,1],indexes[x,y,0]]

现在执行与简单的 1-liner 相同的操作:

classed = labeled_centers[indexes[:,:,1],indexes[:,:,0]]
© www.soinside.com 2019 - 2024. All rights reserved.