2017-03-14 220 views
1

當在圖像上使用箭頭顯示梯度時,箭頭非常密集。我將如何顯示總體趨勢而不是每個箭頭?使用matplotlib顯示稀疏箭頭箭頭

例如,示出該圖象中的梯度的顫動箭頭:

from PIL import Image 
import numpy as np 
import matplotlib.pyplot as plt 

image = Image.open('test.png') 
array = np.array(image) 
array = array[:,:,1] 
array = array.astype(float) 
dy, dx = np.gradient(array) 

plt.figure(figsize=(10, 10)) 
plt.imshow(array) 
plt.quiver(dx, -dy) 
plt.show() 

enter image description here enter image description here

而我想的箭頭爲更大和稀疏,是這樣的: enter image description here

加入

Y, X = np.mgrid[0:50:5, 0:50:5] 
plt.quiver(X, Y, dx[::5, ::5], -dy[::5, ::5]) 

產生奇怪的結果

enter image description here

回答

1

quiver情節有放慢參數scale。來自♦the documentation

比例:[無| float]
每個箭頭長度單位的數據單位,例如每個繪圖寬度的m/s;較小的參數會使箭頭變長。如果沒有,則使用簡單的自動調節算法,基於平均向量長度和向量數量。

將此比例設置爲一個合理的值,也可以讓圖顯得更好。還要檢查其他參數,如scale_unitsunits

enter image description here

import numpy as np 
import matplotlib.pyplot as plt 

f = lambda x,y, x0,y0, sig: np.exp((-(x-x0)**2- (y-y0)**2)/sig**2) 
X,Y = np.meshgrid(np.arange(50), np.arange(50)) 
array = f(X,Y, 24,24,7.) 

dy, dx = np.gradient(array) 

n = 3 
plt.figure(figsize=(7, 7)) 
plt.imshow(array) 
plt.quiver(X[::n,::n],Y[::n,::n],dx[::n,::n], -dy[::n,::n], 
      np.sqrt(dx[::n,::n]**2+dy[::n,::n]**2), 
      units="xy", scale=0.04, cmap="Reds") 
plt.show()