首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >流图mgrid - Python

流图mgrid - Python
EN

Stack Overflow用户
提问于 2014-01-15 12:15:50
回答 1查看 801关注 0票数 0

我在一个项目中工作,我必须创建一个方法来生成一个具有背景和向量流的图像。因此,我使用来自matplotlib的流图。

代码语言:javascript
复制
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。但如果这样做的话:

代码语言:javascript
复制
y, x = np.mgrid[-1:1:self.width, -1:1:self.height]

它不起作用。我也不知道这个j是什么意思,但这似乎很重要,因为如果我去掉j (即使是静态大小的),它也不能工作。所以,我想知道如何动态地按照self的大小来实现mgrid

提前谢谢你。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-01-15 12:35:44

短答案

j是复数的虚部,并给出了numpy.mgrid要生成的值数。就你而言,以下是你应该写的内容:

代码语言:javascript
复制
y, x = np.mgrid[-1:1:self.width*1j, -1:1:self.height*1j]

长答案

step值在np.mgrid[start:stop:step]中的理解如下:

  • 如果step是真实的,那么它被用作从启动到停止的步骤,而不是包括在内。
  • 如果step是纯虚的(例如5j),则它用作返回的步骤数,其中包括stop值。
  • 如果step是复杂的(例如1+5j),那么我必须说我不明白结果.

j代表一个假想的部分。

示例:

代码语言:javascript
复制
>>> 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])
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21137178

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档