如何获取ndarray的x和y维度 - Numpy / Python

10 投票
3 回答
26276 浏览
提问于 2025-04-17 22:52

我在想,能不能单独获取一个ndarray的x和y维度。我知道可以用 ndarray.shape 来获取一个表示维度的元组,但我该怎么把这个元组分开,分别得到x和y的信息呢?

提前谢谢你。

3 个回答

4

ndarray.shape() 会报错 TypeError: 'tuple' object is not callable.,这是因为它不是一个函数,而是一个值。

你想要做的其实是直接使用 .shape,不需要加上 ()。举个例子:

>> import numpy
>> ndarray = numpy.ndarray((20, 21))
>> ndarray.shape
(20, 21)
>> x, y = ndarray.shape
>> x
20
>> y
21

http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.shape.html

14
height, width = a.shape

不过需要注意的是,ndarray的坐标是用矩阵的方式表示的,也就是用(i,j)来表示,而图像的坐标是用(x,y)来表示的。这两者是相反的。

i, j = y, x  # and not x, y

另外,Python中的元组是可以通过索引来访问的,所以你可以像这样访问不同的维度:

dims = a.shape
height = dims[0]
width = dims[1]
20

你可以使用元组解包。

y, x = a.shape

撰写回答