2014-01-15 52 views
0

我在一個項目中工作,我必須創建一個方法來生成背景和矢量流的圖像。所以,我正在使用來自matplotlib的流圖。Streamplot mgrid - Python

class ImageData(object): 

    def __init__(self, width=400, height=400, range_min=-1, range_max=1): 
     """ 
     The ImageData constructor 
     """ 
     self.width = width 
     self.height = height 
     #The values range each pixel can assume 
     self.range_min = range_min 
     self.range_max = range_max 
     #self.data = np.arange(width*height).reshape(height, width) 
     self.data = [] 
     for i in range(width): 
      self.data.append([0] * height) 

    def generate_images_with_streamline(self, file_path, background): 

     # Getting the vector flow 
     x_vectors = [] 
     y_vectors = [] 
     for i in range(self.width): 
      x_vectors.append([0.0] * self.height) 
      y_vectors.append([0.0] * self.height) 

     for x in range(1, self.width-1): 
      for y in range(1, self.height-1): 
       vector = self.data[x][y] 
       x_vectors[x][y] = vector[0].item(0) 
       y_vectors[x][y] = vector[1].item(0) 

     u_coord = np.array(x_vectors) 
     v_coord = np.array(y_vectors) 

     # Static image size 
     y, x = np.mgrid[-1:1:400j, -1:1:400j] 

     # Background + vector flow 
     mg = mpimg.imread(background) 

     plt.figure() 
     plt.imshow(mg, extent=[-1, 1, -1, 1]) 

     plt.streamplot(x, y, u_coord, v_coord, color='y', density=2, cmap=plt.cm.autumn) 
     plt.savefig(file_path+'Streamplot.png') 
     plt.close() 

的問題是,因爲我的np.mgrid應因人而異從-1到1,並有self.widthself.height。但如果這樣做:

y, x = np.mgrid[-1:1:self.width, -1:1:self.height] 

它不起作用。也不知道這是什麼意思,但這似乎是重要的,因爲如果我這脫掉了j(即使有一個靜態大小),它也不起作用。所以,我想知道如何做到這一點mgrid是動態的,跟着自我大小。

預先感謝您。

回答

2

簡短的回答

j是一個複數的虛部,並給出numpy.mgridnumber of values to generate。在你的情況,這裏是你應該寫什麼:

y, x = np.mgrid[-1:1:self.width*1j, -1:1:self.height*1j] 

龍答案

stepnp.mgrid[start:stop:step]值應作如下理解:

  • 如果step是真實的,那麼它是用作從開始到停止的步進,不包括在內。
  • 如果step是純虛數(例如5j),則將其用作要返回的步數,包括stop值。
  • 如果step是複雜的,(例如1+5j),以及我必須說,我不明白的結果...

j是虛部。

例子:

>>> np.mgrid[-1:1:0.5] # values starting at -1, using 0.5 as step, up to 1 (not included) 
array([-1. , -0.5, 0. , 0.5]) 
>>> np.mgrid[-1:1:4j] # values starting at -1 up to +1, 4 values requested 
array([-1.  , -0.33333333, 0.33333333, 1.  ]) 
>>> np.mgrid[-1:1:1+4j] # ??? 
array([-1.  , -0.3596118 , 0.28077641, 0.92116461]) 
+0

@pceccon暫無評論?我的回答是否解決了您的問題?如果是這樣,請你接受嗎? –

+0

接受!非常感謝你!對不起,我來晚了。 :S – pceccon

+0

沒問題! ;-) –