title: Image Gradient Vector Field in Python
body: <p>I am trying to get the <a href="http://upload.wikimedia.org/wikipedia/commons/thumb/0/0f/Gradient2.svg/566px-Gradient2.svg.png" rel="noreferrer">Gradient Vector Field</a> of an image using Python (similar to <a href="https://stackoverflow.com/questions/10416918/compute-gradient-vector-field-of-an-image">this matlab question</a>).</p>
  
  <p>This is the original image:
  <img src="https://i.stack.imgur.com/y7XgK.png" alt="http:/ /dcc.fceia.unr.edu.ar/~rbaravalle/gradient/test.png"></p>
  
  <p>Here is my code:</p>
  
  <pre><code>import numpy as np
  import matplotlib.pyplot as plt
  import Image
  from PIL import ImageFilter
  
  I = Image.open('test.png').transpose(Image.FLIP_TOP_BOTTOM)
  I = I.filter(ImageFilter.BLUR)
  p = np.asarray(I)
  w,h = I.size
  y, x = np.mgrid[0:h:500j, 0:w:500j]
  
  dy, dx = np.gradient(p)
  skip = (slice(None, None, 3), slice(None, None, 3))
  
  fig, ax = plt.subplots()
  im = ax.imshow(I, extent=[x.min(), x.max(), y.min(), y.max()])
  ax.quiver(x[skip], y[skip], dx[skip], dy[skip])
  
  ax.set(aspect=1, title='Quiver Plot')
  plt.show()
  </code></pre>
  
  <p>This is the result:
  <img src="https://i.stack.imgur.com/gGiEe.png" alt="http://dcc.fceia.unr.edu.ar/~rbaravalle/gradient/result.png"></p>
  
  <p>The problem is that the vectors seem to be incorrect. This point gets more clear when you zoom in the image:</p>
  
  <p><img src="https://i.stack.imgur.com/DWuwY.png" alt="http://dcc.fceia.unr.edu.ar/~rbaravalle/gradient/result2.png"></p>
  
  <p>Why do some of the vectors point to the center as expected, while others do not?</p>
  
  <p>Maybe there is an issue with the result of the call to <code>np.gradient</code>?</p>