numpy.meshgrid 和 numpy.mgrid 用于返回包含坐标向量的坐标矩阵. 当坐标矩阵为二维时, 可用于在图像变形时构建网格.
实例一
from __future__ import print_function import numpy as np grid_y1, grid_x1 = np.meshgrid(range(5), range(3)) grid_x2, grid_y2 = np.mgrid[0:3, 0:5] # Two arrays are element-wise equal within a tolerance. print ("grid_x1 == grid_x2?", np.allclose(grid_x1, grid_x2)) # True. print ("grid_y1 == grid_y2?", np.allclose(grid_y2, grid_y2)) # True.
注意, 对于 np.meshgrid(range(5), range(3)),
* 返回两个数组 grid_y1和grid_x1,形状均为 3 x 5, 不是 5 x 3 ;
* 返回的第一个数组元素来自 range(5),即 3 行,每行均为 [0, 1, 2, 3, 4] ;
* 返回的第二个数组元素来自 range(3), 即 5 列,每列均为[0,1,2]
实例二
from __future__ import print_function import numpy as np grid_y1, grid_x1 = np.meshgrid(np.linspace(0,1,200), np.linspace(0,1,100)) # output 100 x 200 array grid_x2, grid_y2 = np.mgrid[0:1:100j, 0:1:200j] # output 100 x 200 array # Two arrays are element-wise equal within a tolerance. print ("grid_x1 == grid_x2?", np.allclose(grid_x1, grid_x2)) # True. print ("grid_y1 == grid_y2?", np.allclose(grid_y2, grid_y2)) # True.
注:
grid_y1, grid_x1 均为 100 x 200 数组.
grid_y1 数组有 100 行, 每行均为 np.linspace(0,1,200), 与 grid_y2 相同 ;
grid_x1 数组有 200 列, 每列均为 np.linspace(0,1,100), 与 grid_x2 相同 ;
0:1:100j 索引表示包含两端即 0 和 1 , 均分为 100 个点 , 与 np.linspace(0,1,100) 含义相同.
原文地址:https://www.cnblogs.com/klchang/p/10633972.html
时间: 2024-11-09 05:53:14