Skip to main content
 首页 » 编程设计

python之在图像上叠加 matplotlib quiver

2024年08月21日32davidwang456

我试图在图像上叠加箭袋渐变箭头,但由于原点位置不同,它们看起来不正确。我该如何解决这个问题?

这是一个例子。左边的图像是我期望的渐变,但是当我将它们绘制在图像之上时,由于原点位置的变化,它们指向错误的方向。

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() 

请您参考如下方法:

如果您希望获得与单独绘制箭头相同的绘图方向,您可以更改 origin of the image通过将 origin='lower' 添加到 imshow 调用中:

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

如果你想保持图像原点在左上角,你可以在调用 plt.quiver 时改变箭头的方向:

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