python 中np.squeeze的用法

当处理数组时,有时候我们希望将形状中维度为1的维度去除,使得数组更加紧凑。np.squeeze函数可以实现这个目的。

1函数参数

numpy.squeeze(a, axis=None)

其中,a表示输入的数组,axis表示要去除的维度的索引或索引列表。如果不指定axis参数,则会去除所有维度为1的维度。

2.常见用法

1.去除所有维度为1的维度

a = np.array([[[1, 2, 3]]])
b = np.squeeze(a)
print(b.shape)

#输出:(3,)

详细例子:

import numpy as np

approx = np.array([[[10, 20]], [[30, 40]], [[50, 60]], [[70, 80]]])
print(approx.shape)  # 输出:(1, 4, 2)

corner_points = np.squeeze(approx)
print(corner_points.shape)  # 输出:(4, 2)

print(corner_points)

输出:

(1, 4, 2)
(4, 2)
[[10 20]
 [30 40]
 [50 60]
 [70 80]]

2.去除指定维度的1维度

a = np.array([[[1, 2, 3]]])
b = np.squeeze(a, axis=0)
print(b.shape)  

# 输出:(1, 3)

c = np.squeeze(a, axis=1)
print(c.shape)  

# 输出:(1, 3)

3.当维度不为1时,不会有任何改变

a = np.array([[1, 2, 3][1,2,3]])
b = np.squeeze(a)
print(b.shape)  

# 输出:(2, 3)

通过使用np.squeeze函数,可以方便地去除数组中不必要的维度,使得数组更加紧凑。在处理轮廓坐标等情况下,它常用于将多维数组转换为一维数组形式。