gpt4 book ai didi

python - 将浮点坐标添加到 numpy 数组

转载 作者:行者123 更新时间:2023-12-03 19:13:18 26 4
gpt4 key购买 nike

我想通过将基于坐标质心的强度拆分为相邻像素来将浮点坐标添加到 numpy 数组中。

以整数为例:

import numpy as np

arr = np.zeros((5, 5), dtype=float)

coord = [2, 2]
arr[coord[0], coord[1]] = 1

arr
>>> array([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])

但是,当 coord 时,我想在相邻像素之间分配强度。是 float 数据,例如。 coord = [2.2, 1.7] .

我已经考虑使用高斯,例如:
grid = np.meshgrid(*[np.arange(i) for i in arr.shape], indexing='ij')

out = np.exp(-np.dstack([(grid[i]-c)**2 for i, c in enumerate(coord)]).sum(axis=-1) / 0.5**2)

这给出了很好的结果,但对于 3d 数据和数千个点来说变得很慢。

任何建议或想法将不胜感激,谢谢。

根据@rpoleski 的建议,取一个局部区域并按距离应用加权。这是一个好主意,尽管我的实现没有保持坐标的原始质心,例如:
from scipy.ndimage import center_of_mass

coord = [2.2, 1.7]

# get region coords
grid = np.meshgrid(*[range(2) for i in coord], indexing='ij')
# difference Euclidean distance between coords and coord
delta = np.linalg.norm(np.dstack([g-(c%1) for g, c, in zip(grid, coord)]), axis=-1)

value = 3 # pixel value of original coord
# create final array by 1/delta, ie. closer is weighted more
# normalise by sum of 1/delta
out = value * (1/delta) / (1/delta).sum()

out.sum()
>>> 3.0 # as expected

# but
center_of_mass(out)
>>> (0.34, 0.63) # should be (0.2, 0.7) in this case, ie. from coord

有任何想法吗?

最佳答案

这是一个简单的(因此很可能足够快)解决方案,它保持质心并且总和 = 1:

arr = np.zeros((5, 5), dtype=float)

coord = [2.2, 0.7]

indexes = np.array([[x, y] for x in [int(coord[0]), int(coord[0])+1] for y in [int(coord[1]), int(coord[1])+1]])
values = [1. / (abs(coord[0]-index[0]) * abs(coord[1]-index[1])) for index in indexes]
sum_values = sum(values)
for (value, index) in zip(values, indexes):
arr[index[0], index[1]] = value / sum_values
print(arr)
print(center_of_mass(arr))

这导致:

[[0.   0.   0.   0.   0.  ]
[0. 0. 0. 0. 0. ]
[0. 0.24 0.56 0. 0. ]
[0. 0.06 0.14 0. 0. ]
[0. 0. 0. 0. 0. ]]
(2.2, 1.7)

注意:我使用的是出租车距离 - 它们适用于质心计算。

关于python - 将浮点坐标添加到 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61458395/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com