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()
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With