繁体   English   中英

如何在二维数组(矩阵)中找到局部最大值的索引?

[英]How to find indices of local maximum in a 2d array (matrix)?

我创建了矩阵 x:

import numpy as np
np.random.seed(0)
x = np.random.randint(10, size=(5, 5))

 x=array([[5, 0, 3, 3, 7],
   [9, 3, 5, 2, 4],
   [7, 6, 8, 8, 1],
   [6, 7, 7, 8, 1],
   [5, 9, 8, 9, 4]])

局部最大指数应如下所示:

array([[0, 1, 2, 2, 4, 4],
   [4, 0, 2, 3, 1, 3]])

我已经尝试过像下面的代码这样的方法来找到一个局部最大值,但我越来越困惑,甚至没有接近结果。

for i in range(0,5):
A12=np.r_[ x[1:-1][i] > x[:-2][i] , False]
result12= np.where(A12 == False)
result12=np.asarray(result12)
A22=np.r_[ x[i][1:-1][i] < x[2:][i] , True]
result22= np.where(A22 == True)
result22=np.asarray(result22)
print(np.intersect1d(result12, result22))

这里有一个方法。 如果你检查它,我相信这会对你有所帮助。 我想到的是你也可以把你的二维数组变成一个图像。 像这样:

import numpy as np
import pandas as pd 
import matplotlib.pyplot as plt

np.random.seed(0)
x = np.random.randint(10, size=(5, 5))
plt.matshow(x)

之后,您可以检查 colors 以找到一致性。 你也可以试试这个:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm


np.random.seed(0)
a = np.random.randint(10, size=(5, 5))
a += a[::-1,:]

fig = plt.figure()
ax2 = fig.add_subplot(122)
# 'nearest' interpolation - faithful but blocky
ax2.imshow(a, interpolation='nearest', cmap=cm.Greys_r)

plt.show()

output 将是:像这样

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM