Python 将图像集读取到4D Numpy阵列中,尺寸为(num_img,channel,dim1,dim2)

Python 将图像集读取到4D Numpy阵列中,尺寸为(num_img,channel,dim1,dim2),python,arrays,numpy,Python,Arrays,Numpy,我有一组1000个灰度图像(28x28),我想将它们读入4D numpy数组(图像数量,1,img_dim1,img_dim2)。下面是我的代码,但它不能正常工作。知道如何在代码中解决这个问题吗 from PIL import Image import numpy as np import os mypath=os.path.dirname('path/to/directory/') def load_dataset( ) : data =np.zeros((1000,1,28,28)

我有一组1000个灰度图像(28x28),我想将它们读入4D numpy数组(图像数量,1,img_dim1,img_dim2)。下面是我的代码,但它不能正常工作。知道如何在代码中解决这个问题吗

from PIL import Image
import numpy as np
import os

mypath=os.path.dirname('path/to/directory/')
def load_dataset( ) :
    data =np.zeros((1000,1,28,28), dtype=np.float64)
    for fname in os.listdir(mypath):
        pathname = os.path.join(mypath, fname)
        img = Image.open(pathname)
        data = np.dstack((data, img))
    return data
data=load_dataset()
print(data.shape)

通过使用
append
并添加一个新轴
np.newaxis

from PIL import Image
import numpy as np
import os

mypath=os.path.dirname('path/to/directory/')
def load_dataset( ) :
    data =[]
    for fname in os.listdir(mypath):
        pathname = os.path.join(mypath, fname)
        img = Image.open(pathname)
        img1 = img[np.newaxis,:,:]
        data.append(img1)
    return data

data= load_dataset()
data_x=np.array(data)
print data_x.shape

什么东西坏了?请告诉我们您遇到的问题或错误。为什么要增加维度?您可以
枚举
路径并插入到
数据[i]=img
,因为数据已经预先分配。使用dstack,您基本上是要求它将
omg
附加到
数据
的末尾,而不是插入。在函数外部使用
return
也不清楚。这是如何解决您的问题的?我在“img=Image.open(路径名)”行中得到了“JpegImageFile”对象不可订阅”