[英]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.