Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

superimpose matplotlib quiver on image

I'm trying to superimpose quiver gradient arrows on an image, but since the origin locations are different, they don't look right. How would I fix this?

This is an example. The image to the left are the gradients I expect, but as soon as I draw them on top of an image, they point in the wrong directions because of the change in origin location.

import matplotlib.pyplot as plt
import numpy as np

test_array = np.array([[0, 0, 0, 0, 0],
                       [0, 64, 128, 64, 0],
                       [0, 127, 255, 127, 0],
                       [0, 64, 127, 64, 0],
                       [0, 0, 0, 0, 0]]).astype("float")

dy, dx = np.gradient(test_array)
plt.imshow(test_array)
plt.quiver(dx, dy)
plt.show()

enter image description here enter image description here

like image 662
waspinator Avatar asked Mar 14 '17 02:03

waspinator


1 Answers

If you want to have the same plot orientation that you get with plotting the arrows alone, you can change the origin of the image by adding origin='lower' to the imshow call:

plt.imshow(test_array, origin='lower')

If you want to keep the image origin in the upper left corner, you could just change the direction of the arrows when you call plt.quiver:

dy, dx = np.gradient(test_array)
plt.imshow(test_array)
plt.quiver(dx, -dy)
plt.show()
like image 93
Craig Avatar answered Oct 18 '22 22:10

Craig