簡體   English   中英

3D Numpy Arrays到數組轉換列表

[英]List of 3D Numpy Arrays to Array Conversion

我正在使用來自 PIL 的圖像來打開圖像並將它們加載到尺寸(300,300,3)的 numpy arrays 中。 這些 arrays 附加到列表中,然后我想將此列表轉換為 numpy 數組。 應該工作的一切,都沒有。 我不斷收到奇怪的錯誤:

ValueError: could not broadcast input array from shape (300, 300, 3) into shape (300, 300)

這是一個小示例代碼:

  • 循環前
training_data = []
  • 循環中
image = Image.open(path).resize((300,300),Image.ANTIALIAS)
training_data.append(np.asarray(image))
  • 外環
training_data = np.array(training_data)

簡單的問題是我得到了上面提到的錯誤。 任何幫助深表感謝。

您很可能已經收集了一份不同尺寸的 arrays 列表,可能有些是黑白的,有些是彩色的:

In [17]: alist = []                                                                                  
In [18]: alist.append(np.ones((300,300)))        # bw                                                            
In [19]: alist.append(np.ones((300,300,3)))      # color                                               
In [20]: np.array(alist)                                                                             
/usr/local/bin/ipython3:1: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray
  #!/usr/bin/python3
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-20-7512d762195a> in <module>
----> 1 np.array(alist)

ValueError: could not broadcast input array from shape (300,300,3) into shape (300,300)

當我們嘗試從 arrays 創建一個形狀不同的數組時, v1.19給了我們一個警告。 有時這仍然會給我們一個 object dtype 數組,但是使用這種形狀組合,結果就是你的錯誤。

===

將 arrays 組合成一個的等效方法是使用np.stack 如果有效,結果是一樣的; 如果不是,則錯誤是不同的:

In [21]: np.stack(alist)                                                                             
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-21-724d9c1d0554> in <module>
----> 1 np.stack(alist)

<__array_function__ internals> in stack(*args, **kwargs)

/usr/local/lib/python3.6/dist-packages/numpy/core/shape_base.py in stack(arrays, axis, out)
    425     shapes = {arr.shape for arr in arrays}
    426     if len(shapes) != 1:
--> 427         raise ValueError('all input arrays must have the same shape')
    428 
    429     result_ndim = arrays[0].ndim + 1

ValueError: all input arrays must have the same shape

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM