Python 如何将计算结果存储在np数组中的两个for循环中?

Python 如何将计算结果存储在np数组中的两个for循环中?,python,numpy,for-loop,Python,Numpy,For Loop,我想迭代一幅图像,并将计算出的距离保存在numpy数组np_dist中的限制(x,y)像素和点(300600)之间。目前,所有dist值的结果保存在数组的一个元素中。如何填充每个元素存储一个值的数组 dist_arr = np.empty((width, height)) for x in range(0, width): for y in range(0, height): pixel = (x, y) dist = math.sqrt((300

我想迭代一幅图像,并将计算出的距离保存在numpy数组np_dist中的限制(x,y)像素和点(300600)之间。目前,所有dist值的结果保存在数组的一个元素中。如何填充每个元素存储一个值的数组

dist_arr = np.empty((width, height))
for x in range(0, width): 
    for y in range(0, height): 
        pixel = (x, y) 
        dist = math.sqrt((300 - pixel[0])**2 + (600 - pixel[1])**2) 
        dist_arr[pixel[0], pixel[1]] = dist

尝试+


你的循环没有任何问题:

In [26]: width, height = 4,4
    ...: dist_arr = np.empty((width, height))
    ...: for x in range(0, width):
    ...:     for y in range(0, height):
    ...:         dist = math.sqrt((300 - x)**2 + (600 - y)**2)
    ...:         dist_arr[x, y] = dist
    ...: 
In [27]: dist_arr
Out[27]: 
array([[670.82039325, 669.92611533, 669.03213675, 668.1384587 ],
       [670.37377634, 669.47890183, 668.58432527, 667.69004785],
       [669.92835438, 669.03288409, 668.13771036, 667.24283436],
       [669.48412976, 668.58806451, 667.6922944 , 666.79682063]])
有很多方法可以更快地做到这一点,但它们确实有效

整个数组的值相同
numpy
计算:

In [28]: np.sqrt((300-np.arange(4)[:,None])**2 + (600 - np.arange(4))**2)
Out[28]: 
array([[670.82039325, 669.92611533, 669.03213675, 668.1384587 ],
       [670.37377634, 669.47890183, 668.58432527, 667.69004785],
       [669.92835438, 669.03288409, 668.13771036, 667.24283436],
       [669.48412976, 668.58806451, 667.6922944 , 666.79682063]])
In [28]: np.sqrt((300-np.arange(4)[:,None])**2 + (600 - np.arange(4))**2)
Out[28]: 
array([[670.82039325, 669.92611533, 669.03213675, 668.1384587 ],
       [670.37377634, 669.47890183, 668.58432527, 667.69004785],
       [669.92835438, 669.03288409, 668.13771036, 667.24283436],
       [669.48412976, 668.58806451, 667.6922944 , 666.79682063]])