查找顶部和#x27的二维坐标(行、列);n';元素,然后使用这些坐标在其他数组上使用python执行操作?

查找顶部和#x27的二维坐标(行、列);n';元素,然后使用这些坐标在其他数组上使用python执行操作?,python,arrays,image,numpy,multidimensional-array,Python,Arrays,Image,Numpy,Multidimensional Array,请参阅下面的示例,以便更好地理解我的问题。 假设它们是两个数组A和B: A=array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) B=array([[3,4,12,2], [5,11,1,6], [9,10,7,8]]) 在B中,找到其中前5个元素(12,11,10,9,8)的坐标 预期输出1: coordinates=(0,2) (1,1)

请参阅下面的示例,以便更好地理解我的问题。

假设它们是两个数组A和B:

A=array([[1,2,3,4],
         [5,6,7,8],
         [9,10,11,12]])

B=array([[3,4,12,2],
         [5,11,1,6],
         [9,10,7,8]])
在B中,找到其中前5个元素(12,11,10,9,8)的坐标

预期输出1:

coordinates=(0,2)
            (1,1)
            (2,1)
            (2,0)
            (2,3)
[30,60,100,90,120]
现在,我想把A中坐标(0,2),(1,1),(2,1),(2,0),(2,3)中的元素乘以10

那么预期输出2将是:

coordinates=(0,2)
            (1,1)
            (2,1)
            (2,0)
            (2,3)
[30,60,100,90,120]

使用
numpy.array.ravel
numpy.array.argsort

A.ravel()[B.ravel().argsort()[-5:][::-1]] * 10
输出:

array([ 30,  60, 100,  90, 120])

对于大型阵列,ArgPartition将更加高效:

A=np.random.rand(100,100)
B=np.random.rand(100,100)

%timeit A.ravel()[np.argpartition(B,B.size-5,None)[-5:]] * 10
459 µs ± 37.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit A.ravel()[B.ravel().argsort()[-5:][::-1]] * 10
2.85 ms ± 34.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

获取预期输出1的代码:

C=(B.ravel().argsort()[-5:][::-1])
cord=(np.unravel_index(C, B.shape))
(array([0, 1, 2, 2, 2], dtype=int64), array([2, 1, 1, 0, 3], dtype=int64))

## here 1st array gives the row coordinates and 2nd array gives the column coordinates of top 5 elements in B. In order.
输出

C=(B.ravel().argsort()[-5:][::-1])
cord=(np.unravel_index(C, B.shape))
(array([0, 1, 2, 2, 2], dtype=int64), array([2, 1, 1, 0, 3], dtype=int64))

## here 1st array gives the row coordinates and 2nd array gives the column coordinates of top 5 elements in B. In order.

谢谢你的快速回复。假设A是灰度图像,A中的每个元素表示一个二维段。我必须将“threshold_otsu”应用到元素上,而不是将它们乘以10。那么我应该如何更改代码?将threshold_otsu应用于整个图像的代码是:>>来自skimage.filters import threshold_otsu>>thresh=threshold_otsu(A,16)注意这里我假设A是灰度图像,其中的每个元素都是一个二维段。与其乘以10,不如尝试threshold_otsu(A.ravel()[B.ravel().argsort()[-5:[:-1]],16)?参见第二个答案。在您提到的链接中,@B.M.可能重复。它返回单行中最大值元素的位置。在一维数组中。在这里,我将处理一个二维数组(在实际情况下,我将使用25*38和更多形状数组),并且我想要这个二维数组中最大值的索引/坐标。请注意
np.undravel_index(B.argmax(),B.shape)
此命令帮助我仅获取数组中前1个最大值的坐标,但我不知道如何使用此命令获取前5个最大值的坐标。