Skip to main content
 首页 » 编程设计

python之Numpy 图像数组错误维度 Python 和 Keras

2024年09月07日13leader

我正在构建图像分类器并尝试使用 keras 计算数据集的特征,但我的数组维度格式不正确。我得到了

ValueError: Error when checking : expected input_1 to have 4 dimensions, but got array with shape (324398, 1) 

我的代码是这样的:

import glob 
from keras.applications.resnet50 import ResNet50 
 
def extract_resnet(X):   
    # X : images numpy array 
    resnet_model = ResNet50(input_shape=(image_h, image_w, 3),  
    weights='imagenet', include_top=False)  # Since top layer is the fc layer used for predictions 
    features_array = resnet_model.predict(X) 
    return features_array 
filelist = glob.glob('dataset/*.jpg') 
myarray = np.array([np.array(Image.open(fname)) for fname in filelist]) 
print(extract_resnet(myarray)) 

所以看起来由于某种原因图像数组只有二维,而它应该是 4 维的。我如何转换 myarray 以便它能够与特征提取器一起工作?

请您参考如下方法:

首先,确保 dataset 目录中的所有图像具有相同的大小 (image_h, image_w, 3):

print([np.array(Image.open(fname)).shape for fname in filelist]) 

如果不是,您将无法进行小批量处理,因此您只需选择合适图像的子集。如果大小合适,您可以手动调整数组的形状:

myarray = myarray.reshape([-1, image_h, image_w, 3]) 

... 以完全匹配 ResNet 规范。