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

xwbd5t1u  于 2024-01-05  发布在  Python
关注(0)|答案(1)|浏览(175)

我创建了矩阵x:

  1. import numpy as np
  2. np.random.seed(0)
  3. x = np.random.randint(10, size=(5, 5))
  4. x=array([[5, 0, 3, 3, 7],
  5. [9, 3, 5, 2, 4],
  6. [7, 6, 8, 8, 1],
  7. [6, 7, 7, 8, 1],
  8. [5, 9, 8, 9, 4]])

字符串
局部最大值索引应该是这样的:

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


我已经尝试了类似下面代码的方法来找到局部最大值,但我越来越困惑,甚至没有接近结果。

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

xriantvc

xriantvc1#

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

  1. import numpy as np
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. np.random.seed(0)
  5. x = np.random.randint(10, size=(5, 5))
  6. plt.matshow(x)

字符串
之后,您可以检查颜色以找到连贯性。您也可以尝试此操作:

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import matplotlib.cm as cm
  4. np.random.seed(0)
  5. a = np.random.randint(10, size=(5, 5))
  6. a += a[::-1,:]
  7. fig = plt.figure()
  8. ax2 = fig.add_subplot(122)
  9. # 'nearest' interpolation - faithful but blocky
  10. ax2.imshow(a, interpolation='nearest', cmap=cm.Greys_r)
  11. plt.show()


输出将是:like this

展开查看全部

相关问题