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

时间:2021-09-10 21:41:57

I'm wondering if I can get the x and y dimensions of a ndarray separately. I know that I can use ndarray.shape to get a tuple representing the dimensions, but how can I separate this in x and y information?

我想知道我是否可以分别获得ndarray的x和y维度。我知道我可以使用ndarray.shape来获取表示维度的元组,但是如何在x和y信息中分离它?

Thank you in advance.

先谢谢你。

3 个解决方案

#1


9  

You can use tuple unpacking.

你可以使用元组解包。

y, x = a.shape

#2


4  

height, width = a.shape

Note, however, that ndarray has matrix coordinates (i,j), which are opposite to image coordinates (x,y). That is:

但是请注意,ndarray具有矩阵坐标(i,j),它与图像坐标(x,y)相反。那是:

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

Also, Python tuples support indexing, so you can access separate dimensions like this:

此外,Python元组支持索引,因此您可以访问单独的维度,如下所示:

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

#3


2  

ndarray.shape() will throw a TypeError: 'tuple' object is not callable. because it's not a function, it's a value.

ndarray.shape()将抛出一个TypeError:'tuple'对象不可调用。因为它不是一个功能,它是一个价值。

What you want to do is just tuple unpack .shape without the (). Example:

你想要做的只是在没有()的情况下解包.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

#1


9  

You can use tuple unpacking.

你可以使用元组解包。

y, x = a.shape

#2


4  

height, width = a.shape

Note, however, that ndarray has matrix coordinates (i,j), which are opposite to image coordinates (x,y). That is:

但是请注意,ndarray具有矩阵坐标(i,j),它与图像坐标(x,y)相反。那是:

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

Also, Python tuples support indexing, so you can access separate dimensions like this:

此外,Python元组支持索引,因此您可以访问单独的维度,如下所示:

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

#3


2  

ndarray.shape() will throw a TypeError: 'tuple' object is not callable. because it's not a function, it's a value.

ndarray.shape()将抛出一个TypeError:'tuple'对象不可调用。因为它不是一个功能,它是一个价值。

What you want to do is just tuple unpack .shape without the (). Example:

你想要做的只是在没有()的情况下解包.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