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.width和self.height。但如果這樣做:
y, x = np.mgrid[-1:1:self.width, -1:1:self.height]
它不起作用。也不知道這是什麼意思,但這似乎是重要的,因爲如果我這脫掉了j(即使有一個靜態大小),它也不起作用。所以,我想知道如何做到這一點mgrid是動態的,跟着自我大小。
預先感謝您。
@pceccon暫無評論?我的回答是否解決了您的問題?如果是這樣,請你接受嗎? –
接受!非常感謝你!對不起,我來晚了。 :S – pceccon
沒問題! ;-) –