我编写了一个函数,将数组中每个元素的索引添加到元素中。
例子:
第一个元素是 [10,11],索引是 [0,0] -> 变为 [0,0,10,11]
第二个元素是 [12,13],索引是 [1,0] -> 变成 [1,0,12,13]
如何优化此功能?有没有更简单的写法?任何改进/建议将不胜感激!
我的项目:我正在使用光流来获取幅度数组(u,v),它们表示每个像素的光流矢量分量。我想将像素的位置 (x,y) 添加到数组中,以便获得 (x, y, u, v) 的数组。注意:(x,y) 位置与索引值相同,这样会更容易一些。
这是我的代码:
def vec_4D (mag_2D):
vec_4D = np.zeros((mag_2D.shape[0],mag_2D.shape[1],4))
x = 0
y = 0
for row in vec_4D:
for col in row:
col[0] = x
col[1] = y
col[2] = mag_2D[y][x][0]
col[3] = mag_2D[y][x][1]
x += 1
x=0
y+=1
return(vec_4D)
mag_2D = np.array([[[10,11], [12,13], [14,15]], [[16,17], [18,19], [20,21]]])
print(vec_4D(mag_2D))
Input array:
[[[10 11]
[12 13]
[14 15]]
[[16 17]
[18 19]
[20 21]]]
Output array:
[[[ 0. 0. 10. 11.]
[ 1. 0. 12. 13.]
[ 2. 0. 14. 15.]]
[[ 0. 1. 16. 17.]
[ 1. 1. 18. 19.]
[ 2. 1. 20. 21.]]]