In 'gradient' function in MMA, two methods are given to reproduce Matlab's gradient()
function. I thought that GradientFilter[]
and GradientOrientationFilter[]
could also be used, but half of the orientations are rotated by $\pi$ when I tried it:
grad[mat_] := Module[{gradPhi, gradMag, Sx, Sy},
gradPhi = ImageData@GradientOrientationFilter[Image@mat, 2];
gradMag = ImageData@GradientFilter[Image@mat, 2];
{MapThread[#1*Cos[#2] &, {gradMag, gradPhi}, 2],
MapThread[#1*Sin[#2] &, {gradMag, gradPhi}, 2]}
]
Tested with the example from that question:
y = x = Range[-2, 2, 0.2];
z = x Exp[-x^2 - #^2] & /@ y // Transpose;
pxy = grad[z];
ListContourPlot[z\[Transpose], PlotRange -> All,
ContourShading -> None, Contours -> 9,
ContourStyle -> ({Thickness[0.005], ColorData["Rainbow"]@#} &) /@
Rescale@Array[# &, 10], InterpolationOrder -> 2,
DataRange -> {{-2, 2}, {-2, 2}}]~Show~
ListVectorPlot[Transpose[pxy, {3, 1, 2}],
DataRange -> {{-2, 2}, {-2, 2}}, VectorColorFunction -> "Rainbow"]
Should this approach work, or am I confusing two different "kinds" of gradients/gradient functions?
GradientOrientationFilter
returns the angle of a vector parallel to the gradient, which means it may be off by $\pi$. In fact, the documentation states that the angle will be in $(-\pi/2,\pi/2]$. (Side note: the filter functions should accept the matrices themselves, removing the need for the conversion to an image) $\endgroup$