Reputation: 1375
I need to compute the gradient of a matrix (3,3)
, say a=array([[1,4,2],[6,2,4],[7,5,1]])
.
I simply use:
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. ]])
I know that a way for computing the gradient of a matrix is by convolution with a mask for each direction, but results are different
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]])
Where is the error?
Upvotes: 2
Views: 3207
Reputation: 272527
With an image this small (3x3), all but the centre pixel are going to be subject to boundary conditions, making the results pretty meaningless.
But anyway, a quick look at the documentation for numpy.gradient
reveals:
The gradient is computed using central differences in the interior and first differences at the boundaries.
In other words, it doesn't use a fixed convolution kernel across the entire image. It sounds like it simply does (array(i+1,j) - array(i-1,j)) / 2
for interior points, and (array(i,j) - array(i-1,j)
for boundary points.
Upvotes: 5