Dan*_*ard 3 python arrays numpy python-2.7
我在 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()
Run Code Online (Sandbox Code Playgroud)
其作用是生成一张具有一定背景噪声水平的图像和一个圆形对称源。图像上有一个以 40 像素为半径的圆。
我需要知道的是如何找到该圆圈内最高值像素的位置。我知道如何找到圆中的最大值,但不知道[i,j]它的位置。
谢谢你!
我的问题已被 stackoverflow 标记为潜在的重复问题,但这不包含我需要的位置限制。
一种解决方案是将圆周围的所有元素“清零”,然后简单地取整个数组的最大值。看起来你的半径是 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
Run Code Online (Sandbox Code Playgroud)
现在创建您的图像。然后找到最小值并将其设置为边界之外的每个值。如果圆外有一个像素大于圆内的最大值,则现在将其设置为小得多的值。
x_min = np.min(x)
x[mask] = x_min
Run Code Online (Sandbox Code Playgroud)
所以你的图像看起来像
现在只取最大值
print np.max(x)
6.4648628255130571
Run Code Online (Sandbox Code Playgroud)
这个解决方案很好,因为它避免了循环,这基本上违背了使用 numpy 的初衷。
编辑:
抱歉,您说您想要最大值的索引。上面的解决方案是一样的,只是解开索引。
>>> i, j = np.unravel_index(x.argmax(), x.shape)
>>> print "{} {}".format(i, j)
23 32
>>> np.max(x) == x[i,j]
True
Run Code Online (Sandbox Code Playgroud)