在用 python 进行图像处理的时候,为了提高执行效率,必定会用到 numpy 数据类型,以下介绍了图像处理中 numpy 中常用的语法,希望对大家有帮助。
1. numpy 倒置数组(第一个值到最后一个值,最后一个值到第一个值)
In [2]: a = np.random.randint(0, 20, (6, 2))
In [3]: a
Out[3]:
array([[ 8, 16],
[16, 13],
[12, 4],
[13, 7],
[ 7, 6],
[ 6, 3]])
In [4]: a[::-1]
Out[4]:
array([[ 6, 3],
[ 7, 6],
[13, 7],
[12, 4],
[16, 13],
[ 8, 16]])
2. numpy 对调 x 和 y 坐标的顺序
In [7]: a = np.random.randint(0, 20, (6, 2))
In [8]: a
Out[8]:
array([[11, 19],
[17, 15],
[ 8, 14],
[15, 12],
[17, 6],
[ 9, 3]])
In [9]: a[:, ::-1]
Out[9]:
array([[19, 11],
[15, 17],
[14, 8],
[12, 15],
[ 6, 17],
[ 3, 9]])
3. 列表中的数组合成一个数组
In [22]: a = np.random.randint(0, 20, (3, 2, 2))
In [23]: a
Out[23]:
array([[[10, 9],
[15, 10]],
[[ 5, 18],
[ 5, 7]],
[[15, 10],
[ 0, 13]]])
In [24]: b=[a[0],a[1][::-1],a[2]]
In [25]: b
Out[25]:
[array([[10, 9],
[15, 10]]),
array([[ 5, 7],
[ 5, 18]]),
array([[15, 10],
[ 0, 13]])]
In [26]: np.vstack(b)
Out[26]:
array([[10, 9],
[15, 10],
[ 5, 7],
[ 5, 18],
[15, 10],
[ 0, 13]])
4. 数组增加一个维度(2种方法:方法1:使用 np.expand_dims 函数(推荐);方法2:使用 reshape 函数)
In [2]: a = np.random.randint(0, 30, (5, 2))
In [3]: a
Out[3]:
array([[24, 27],
[ 9, 2],
[20, 12],
[23, 26],
[27, 4]])
In [4]: a.shape
Out[4]: (5, 2)
In [5]: b = np.expand_dims(a, 1)
In [6]: b
Out[6]:
array([[[24, 27]],
[[ 9, 2]],
[[20, 12]],
[[23, 26]],
[[27, 4]]])
In [7]: b.shape
Out[7]: (5, 1, 2)
In [8]: c = a.reshape(5, 1, 2)
In [9]: c
Out[9]:
array([[[24, 27]],
[[ 9, 2]],
[[20, 12]],
[[23, 26]],
[[27, 4]]])
In [10]: c.shape
Out[10]: (5, 1, 2)
未完待续~