Issue
This is my code...
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)
As you can see, i have an ndarray in the var named train_X, and... i read an image and reshape it into a vector of one dimention, and when i try to append into the ndarray train_X, and i got this error:
zero-dimensional arrays cannot be concatenated
I just want to concatenate the multiple arrays "vectorized_img" into the train_X ndarray in horizontal
Solution
In [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
just calls np.concatenate
. One argument has shape (), the other (4,1). The error is that it can't join those.
np.ndarray([])
is NOT a clone of []
, and np.append
is not a clone of list append
. concatenate
says that the number of dimensions must match, and the size of the dimensions must also match (except for the concatenate one).
To join 'columns' we need to start with a 'column'
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)
Or we could start with (0,1) and join on axis=0
.
But it's faster, and less prone to errors it we stick with 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.]])
Answered By - hpaulj
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.