1
$\begingroup$

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"]
This Attempt Correct
This method enter image description here

Should this approach work, or am I confusing two different "kinds" of gradients/gradient functions?

$\endgroup$
2
  • 1
    $\begingroup$ According to the documentation, 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$
    – Lukas Lang
    Jun 25, 2022 at 23:22
  • $\begingroup$ @LukasLang Hm right, I guess if it's parallel to the gradient, there's no way to know if the gradient is $+\frac{\pi}{2}$ or $-\frac{\pi}{2}$ off of that. That seems like a poor design decision... $\endgroup$
    – ZachB
    Jun 26, 2022 at 2:55

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.