Python 如何将Numpy从(876,)重塑为(876256,3)?
我有一个包含876个图像的numpy数组。每个图像的大小为256x256x3。当我打印阵列的形状时,我得到了(876,),我想将其重新整形为(876256,3) 当我尝试使用arrary.Reformate(-1256256,3)时,我遇到了一个错误,即无法将(876,)的数组整形为(876256,3) 以下是代码片段:Python 如何将Numpy从(876,)重塑为(876256,3)?,python,python-3.x,numpy,Python,Python 3.x,Numpy,我有一个包含876个图像的numpy数组。每个图像的大小为256x256x3。当我打印阵列的形状时,我得到了(876,),我想将其重新整形为(876256,3) 当我尝试使用arrary.Reformate(-1256256,3)时,我遇到了一个错误,即无法将(876,)的数组整形为(876256,3) 以下是代码片段: for x in trainList: #print(x[0]) #samples = [] #samples.append(x[0]) nam
for x in trainList:
#print(x[0])
#samples = []
#samples.append(x[0])
name = glob.glob("./"+str(TrainFolder)+"/"+x[0])
img = img_to_array(load_img(name[0], color_mode='rgb', target_size=[im_width,im_height]))
#samples.append(img)
#samples.append(x[1])
temp = [x[0],img,x[1]]
trainSet.append(temp)
testList[:] = [os.path.splitext(os.path.basename(x))[0] for x in testList]
for x in testList:
#print(x)
#samples = []
#samples.append(x)
#img = cv2.imread("./TestImages/"+x+".jpg")
#img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
name = glob.glob("./TestImages/"+x+"*")
img = img_to_array(load_img(name[0], color_mode='rgb', target_size=[im_width,im_height]))
#samples.append(img)
temp = [x,img]
testSet.append(temp)
print("Train Data Shape "+str(len(trainSet)))
print("Test Data Shape "+str(len(testSet)))
trainSet = np.asarray(trainSet)
testSet = np.asarray(testSet)
print("Train Data Shape "+str(trainSet.shape))
print("Test Data Shape "+str(testSet.shape))
X_train, X_test, y_train, y_test = train_test_split(trainSet[:,1], trainSet[:,2], test_size=0.33)
print(X_train.shape,y_train.shape)
print(X_test.shape,y_test.shape)
请提供解决方案。您通过添加(列表)来创建
列车组
看起来x
是一种或多种字符串,用于构造文件名img
是通过加载图像创建的数组。所以temp
是一个列表,是字符串和数组的混合体
trainSet = np.asarray(trainSet)
给定该输入列表,该数组必然是1d对象数据类型数组。它无法从该列表生成多维数组
testSet
是一个不同的列表,但仍然是字符串和数组的混合体:
temp = [x,img]
testSet.append(temp)
让我们试着重现一下
In [708]: alist = []
In [709]: alist.append(['x0', np.ones((2,3),int), 'x1'])
In [710]: alist.append(['x0', np.ones((2,3),int), 'x1'])
In [711]: alist
Out[711]:
[['x0', array([[1, 1, 1],
[1, 1, 1]]), 'x1'], ['x0', array([[1, 1, 1],
[1, 1, 1]]), 'x1']]
In [712]: np.array(alist)
Out[712]:
array([['x0', array([[1, 1, 1],
[1, 1, 1]]), 'x1'],
['x0', array([[1, 1, 1],
[1, 1, 1]]), 'x1']], dtype=object)
In [713]: _.shape
Out[713]: (2, 3)
好吧,我本来以为是(2,)型的,结果是(2,3)。所以我必须停止阅读你的代码
我可以使用索引和堆栈提取数组部分:
In [718]: np.stack(_712[:,1])
Out[718]:
array([[[1, 1, 1],
[1, 1, 1]],
[[1, 1, 1],
[1, 1, 1]]])
In [719]: _.shape
Out[719]: (2, 2, 3)
在任何情况下,如果没有有关进入np.array(…)
调用的列表的更多信息,我们都无法提供帮助。或者至少是您试图重塑的阵列的一些信息 你的图片是什么格式的?您可以发布加载图像并创建此数组的代码吗?添加了代码。现在请看这个问题。您是否也可以将img\u的定义发布到数组
和load\u img
请?它们是加载图像并转换到数组的keras函数。重塑
无法更改元素总数。我怀疑您的(876,)
形状数组是对象数据类型(检查是否包含数组)。但是一个或多个阵列不是expet(256256,3)形状,因此np。asarray
无法生成预期的4d阵列。你可以试试np.stack(你的数组)
。如果它给出了一个错误,那将证实我的假设。
In [718]: np.stack(_712[:,1])
Out[718]:
array([[[1, 1, 1],
[1, 1, 1]],
[[1, 1, 1],
[1, 1, 1]]])
In [719]: _.shape
Out[719]: (2, 2, 3)