Skip to main content
 首页 » 编程设计

python之如何优雅地归一化 np.gradient 的每个向量

2024年10月01日7davidwang456

使用 numpy 梯度函数,可以获得一个数组列表。例如。在 3 个维度中对应于 x、y、z 轴的 3 个数组。我想标准化每个元素的渐变。

我现在拥有的是:

gradient = np.gradient(self.image) 
gradient_norm = np.sqrt(sum(x**2 for x gradient)) 
for dim in gradient: 
    np.divide(dim, gradient_norm, out=dim) 
    np.nan_to_num(dim, copy=False) 

对于我认为不是异国情调的问题,它似乎非常冗长和不雅。此外,上面的内容做了相当多的复制,我想避免(作为奖励)。

请您参考如下方法:

使用np.linalg.norm 计算范数并简单地迭代除法 -

norms = np.linalg.norm(gradient,axis=0) 
gradient = [np.where(norms==0,0,i/norms) for i in gradient] 

或者,如果您不介意将 n+1 暗数组作为输出 -

out = np.where(norms==0,0,gradient/norms)