gpt4 book ai didi

python - 通过卷积掩码计算梯度

转载 作者:行者123 更新时间:2023-11-28 22:02:43 26 4
gpt4 key购买 nike

我需要计算矩阵 (3,3) 的梯度,比如 a=array([[1,4,2],[6,2,4], [7,5,1]]).

我只是使用:

from numpy import *
dx,dy = gradient(a)
>>> dx
array([[ 5. , -2. , 2. ],
[ 3. , 0.5, -0.5],
[ 1. , 3. , -3. ]])
>>> dy
array([[ 3. , 0.5, -2. ],
[-4. , -1. , 2. ],
[-2. , -3. , -4. ]])

我知道计算矩阵梯度的一种方法是在每个方向上与掩码进行卷积,但结果不同

from scipy import ndimage
mx=array([[-1,0,1],[-1,0,1],[-1,0,1]])
my=array([[-1,-1,-1],[0,0,0],[1,1,1]])
cx=ndimage.convolve(a,mx)
cy=ndimage.convolve(a,my)
>>> cx
array([[-2, 0, 2],
[ 3, 7, 4],
[ 8, 14, 6]])
>>> cy
array([[ -8, -5, -2],
[-13, -6, 1],
[ -5, -1, 3]])

哪里出错了?

最佳答案

对于这么小的图像 (3x3),除了中心像素之外的所有像素都将受到边界条件的影响,从而使结果变得毫无意义。

但无论如何,快速浏览一下the documentation for numpy.gradient揭示:

The gradient is computed using central differences in the interior and first differences at the boundaries.

换句话说,它不会在整个图像上使用固定的卷积核。听起来它只是对内部点执行 (array(i+1,j) - array(i-1,j))/2(array(i,j) - array(i-1,j) 用于边界点。

关于python - 通过卷积掩码计算梯度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10898229/

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