这是我的代码…
image_paths = dt_labels['image']
train_X = np.ndarray([])
for image_path in image_paths:
path = './Dataset/' + image_path
img = cv2.imread(path, 0)
vectorized_img = img.reshape(img.shape[0] * img.shape[1], 1)
train_X = np.append(train_X, vectorized_img, axis=1)
正如你所看到的,我在var中有一个名为train_X的数组,和…我读取图像并将其重塑为一维向量,当我尝试追加到ndarray train_X时,我得到了这个错误:
不能连接零维数组
我只是想连接多个数组&;vectorized_img&;在水平
中插入train_X narrayIn [103]: train_X = np.ndarray([])
...: print(train_X.shape)
...: for i in range(3):
...: vectorized_img = np.ones((4, 1))
...: train_X = np.append(train_X, vectorized_img, axis=1)
...:
()
Traceback (most recent call last):
File "<ipython-input-103-26d2205beb4e>", line 5, in <module>
train_X = np.append(train_X, vectorized_img, axis=1)
File "<__array_function__ internals>", line 5, in append
File "/usr/local/lib/python3.8/dist-packages/numpy/lib/function_base.py", line 4745, in append
return concatenate((arr, values), axis=axis)
File "<__array_function__ internals>", line 5, in concatenate
ValueError: zero-dimensional arrays cannot be concatenated
np.append
只调用np.concatenate
。一个参数具有shape(),另一个参数具有shape(4,1)。错误是它不能连接那些
np.ndarray([])
不是[]
的克隆,np.append
也不是列表append
的克隆。concatenate
表示维度的数量必须匹配,维度的大小也必须匹配(除了连接的维度)。
要连接"列",我们需要以"列"开头
In [111]: train_X = np.ones((4,0))
...: for i in range(3):
...: vectorized_img = np.ones((4, 1))
...: train_X = np.append(train_X, vectorized_img, axis=1)
...: train_X.shape
Out[111]: (4, 3)
或者我们可以从(0,1)开始,然后连接到axis=0
。
但是如果我们坚持使用list append:
,它会更快,而且更不容易出错In [114]: alist = []
...: for i in range(3):
...: vectorized_img = np.ones((4, 1))
...: alist.append(vectorized_img)
...: np.concatenate(alist, axis=1)
Out[114]:
array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])