【问题标题】:How to find the maximum value of a numpy array, with location restrictions?如何找到具有位置限制的 numpy 数组的最大值?
【发布时间】:2017-12-26 09:01:10
【问题描述】:

我在 python 2.7 中有一个 numpy 数组,我使用 imshow() 函数对其进行可视化。生成数组的代码如下:

from pylab import *
r0 = 3.0
S0 = 10.0
x = zeros((101,101))
noiseimg = zeros((101,101))
for i in range(101):
    for j in range(101):
        noiseimg[i,j] = noiseimg[i,j] + normal(3,1)
mean_i = randint(0,101)
mean_j = randint(0,101)

for i in range(101):
    for j in range(101):
        r = ((i-mean_i)**2 + (j-mean_j)**2)**0.5
        x[i,j] = S0*(1+(r/r0)**2)**-1.5
        x[i,j] = x[i,j] + noiseimg[i,j]
        if (((i-50)**2 + (j-50)**2)**0.5 >= 40) and (((i-50)**2 + (j-50)**2)**0.5 <= 41):
            x[i,j]=0
imshow(x)
show()

它的作用是生成具有一定背景噪声水平和一个圆形对称源的图像。图像中心有一个圆,半径为 40 像素。

我需要知道的是如何找到该圆圈内最高值像素的位置。我知道如何找到圆圈中的最大值,但不知道它的[i,j] 位置。

谢谢!

stackoverflow 已将我的问题标记为potential duplicate,但这不包含我需要的位置限制。

【问题讨论】:

  • 你用什么方法求圆的最大值?
  • 我有一个开始为空的列表,然后 for 循环遍历数组,将每个值附加到列表中,跳过圆圈外的值。然后打印该列表中的最大值。
  • 如果我理解正确的话,我会发布一个应该有效的答案。告诉我,我会做出相应的调整。

标签: python arrays python-2.7 numpy


【解决方案1】:

一种解决方案是将圆圈周围的所有元素“归零”,然后简单地取整个数组的最大值。您的半径似乎是 41,以 (50,50) 为中心。

那你就可以了

import numpy as np

xc, yc = 50, 50
length = 101
radius = 41

y_grid, x_grid = np.ogrid[-xc:length-xc, -yc:length-yc]
mask = x_grid ** 2 + y_grid ** 2 > radius ** 2

现在创建您的图像。然后找到最小值并将其设置为边界之外的每个值。如果圆外的像素大于圆内的最大值,则现在将其设置为小得多的值。

x_min = np.min(x)
x[mask] = x_min

所以你的图像看起来像

现在就取最大值

print np.max(x)
6.4648628255130571

这个解决方案很好,因为它避免了循环,这几乎违背了最初使用 numpy 的目的。

编辑

抱歉,您说您想要最大值的索引。上面的解决方法是一样的,只是解开索引。

>>> i, j = np.unravel_index(x.argmax(), x.shape)
>>> print "{} {}".format(i, j)
23 32
>>> np.max(x) == x[i,j]
True

【讨论】:

    【解决方案2】:
    circleList = []
    indeces = []
    for i in len(x[0]):
        for j in len(x[1]):
            if x[i,j] in circle:    #However you check if pixel is inside circle
                circleList.append(x[i,j])
                indeces.append = ((i,j))
    print np.max(circleList)              #Here is your max
    print indeces(np.argmax(circleList))  #Here are the indeces of the max
    

    应该这样做。

    【讨论】:

      猜你喜欢
      • 2019-07-05
      • 2016-05-05
      • 1970-01-01
      • 2017-02-13
      • 1970-01-01
      • 2014-04-03
      • 2013-06-11
      • 2013-11-21
      • 2019-02-02
      相关资源
      最近更新 更多