将图像集读入4D Numpy数组,其尺寸为(num_img,channel,dim1,dim2)

时间:2016-07-09 23:03:49

标签: 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), 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)

1 个答案:

答案 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