【问题标题】:How many columns/rows in this array?这个数组中有多少列/行?
【发布时间】:2021-09-25 23:10:17
【问题描述】:

我知道这可能是一个愚蠢的问题(请告诉我)。 当我打印出一个形状为 (2, 493, 452) 的数组时,应该有 2 行吧?为什么下面看起来像多行(例如第一行是[ 0 0 0...0 0 0])然后对于第二个输出(2,222836),这意味着有2行和222836列?

(2, 493, 452)
[[[  0   0   0 ...   0   0   0]
  [  1   1   1 ...   1   1   1]
  [  2   2   2 ...   2   2   2]
  ...
  [490 490 490 ... 490 490 490]
  [491 491 491 ... 491 491 491]
  [492 492 492 ... 492 492 492]]

 [[  0   1   2 ... 449 450 451]
  [  0   1   2 ... 449 450 451]
  [  0   1   2 ... 449 450 451]
  ...
  [  0   1   2 ... 449 450 451]
  [  0   1   2 ... 449 450 451]
  [  0   1   2 ... 449 450 451]]]
(2, 222836)
[[  0   0   0 ... 492 492 492]
 [  0   1   2 ... 449 450 451]]

这是我的代码:

original_image=cv2.imread("mickey mouse.jpg")
img=cv2.cvtColor(original_image,cv2.COLOR_BGR2RGB)
vectorized=img.reshape((-1,3))
#print(vectorized.shape)
#print(vectorized)
ind=np.indices((m,n))
print(ind.shape)
print(ind)

ind.resize((2,m*n))
print(ind.shape)
print(ind)

【问题讨论】:

  • 它不是矩阵,它是张量......所以有三个维度......宽度,高度和深度
  • 当你检查[ ]时,它是有道理的。
  • 我更喜欢将第一个维度称为“平面”或“块”,并且只对最后两个维度使用行/列。但是像这样的名字只是为了我们人类的方便。它们不是numpy 代码或文档的一部分。

标签: python numpy


【解决方案1】:

indices 为 2 个维度中的每一个创建“索引”:

ind=np.indices((m,n))
print(ind.shape)
print(ind)

所以结果是一个 (2,m,n) 数组。 ind[9,:,:] 是第一个维度的索引,一个 (m,n) 数组。

其实这应该是reshape,但是它从原来的ind变成了(2, m*n)形状数组。

ind.resize((2,m*n))
print(ind.shape)
print(ind)

在谈论这些索引数组时,行/列没有多大意义。

看一个较小的案例(来自另一个最近的 SO,How to get all indices of NumPy array, but not in a format provided by np.indices()

In [71]: list(np.ndindex(3,2))
Out[71]: [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]
In [72]: np.indices((3,2))
Out[72]: 
array([[[0, 0],
        [1, 1],
        [2, 2]],

       [[0, 1],
        [0, 1],
        [0, 1]]])

meshgrid 做同样的事情,但作为 2 个数组的列表:

In [75]: np.meshgrid(np.arange(3),np.arange(2),indexing='ij')
Out[75]: 
[array([[0, 0],
        [1, 1],
        [2, 2]]),
 array([[0, 1],
        [0, 1],
        [0, 1]])]

【讨论】:

    【解决方案2】:

    当您有一个形状为 (2, 493, 452) 的 numpy 数组并在控制台上将其打印出来时,numpy 会将其打印为 2 个形状为 (493, 452) 的数组。这让我很长一段时间。也许您可能会考虑像 452 个形状为 (2, 493) 的数组这样的原始数组,在这种情况下,您可能会认为控制台输出会有所不同。

    即使控制台输出与您期望的不匹配,形状也将始终由arr.shape 给出。

    【讨论】:

      猜你喜欢
      • 2021-12-04
      • 2013-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-17
      • 2015-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多