我正在尝试创建一个空的numpy数组,并保存从我的设备获得的所有图像。图像形状为numpy(240,320,3)。创建一个空数组来存储这些图像似乎是正确的事情。但是当我尝试追加时,我收到了这个错误:
ValueError: all the input arrays must have same number of dimensions
代码如下:
import numpy as np
# will be appending many images of size (240,320,3)
images = np.empty((0,240,320,3),dtype='uint8')
# filler image to append
image = np.ones((240,320,3),dtype='uint8') * 255
images = np.append(images,image,axis=0)
我需要在此数组中添加许多图像,因此在100
附加后,如果正确完成,图像数组的形状应为(100,240,320,3)
形状。
答案 0 :(得分:2)
优于np.append
:
images = np.empty((100,240,320,3),dtype='uint8')
for i in range(100):
image = ....
images[i,...] = image
或
alist = []
for i in range(100):
image = ....
alist.append(image)
images = np.array(alist)
# or images = np.stack(alist, axis=0) for more control
np.append
只是np.concatenate
的封面。所以每次循环都会生成一个新数组。当您添加第100张图像时,您已经复制了第一张图像100次! np.append
的另一个缺点是您必须调整image
的维度,这是一个常见的错误来源。另一个常见的错误就是让这个初始的空白'阵列形状错误。
答案 1 :(得分:1)
您的images
数组有四个维度,因此您必须nailbuster's blog一个四维项目。为此,只需将新轴添加到image
,如下所示:
images = np.append(images,image[np.newaxis, ...], axis=0)
从某种意义上说,传递轴numpy.append
更像是list.extend
而不是list.append
。