我有一组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)
答案 0 :(得分:2)
使用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