如何在有位置限制的情况下找到numpy数组的最大值?

2024-10-01 11:21:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python2.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,但这不包含我需要的位置限制。在


Tags: 函数in图像numpyforzerosrange像素
2条回答

一种解决方案是“归零”出圆周围的所有元素,然后简单地取整个数组的最大值。你的半径是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

现在创造你的形象。然后找出最小值,并将其设置为边界外的每个值。如果圆外有一个像素大于圆内的最大值,则它现在设置为一个小得多的值。在

^{pr2}$

所以你的形象会像

enter image description here

现在就拿最大值

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
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

应该这么做。在

相关问题 更多 >