我无法使用keras预测单个图像

时间:2018-05-31 18:20:54

标签: keras

我试图用keras预测单个图像。但模型没有拍摄图像。这是我使用的代码:

this

这是我得到的错误:

  

预计dense_1_input有2个维度,但是有阵列形状   (1,150,150,3)

x = cv2.imread('download.png')
x=cv2.resize(x,(150,150))
x = x.reshape((1,) + x.shape)
pred = model.predict_classes(x)
print(pred)

1 个答案:

答案 0 :(得分:0)

对于RGB图像,您的输入应该是这样的:

shape = (IMAGE_HEIGHT, IMAGE_WIDTH, 3)  # height, width, depth

input_layer = Input(shape=shape)
然后,您可以选择展平输入,并将其传递到简单的前馈网络。

flatten = Flatten()(input_layer)
dense = Dense(num_pixels, activation='relu')
dense = Dense(num_classes, activation='softmax')

model = Model(input_layer, dense)
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    return model

(这不是使用keras功能API)。你需要:

from keras.models import Model 

但是,我认为上述模型不能真正适用于任何任务。也许使用相对简单的CNN

input_layer = Input(shape=shape)

# Block 1
x = Conv2D(32, (3, 3), activation='relu', name='block1_conv1')(input_layer)
x = Conv2D(32, (3, 3), activation='relu', name='block1_conv2')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)

# Block 2
x = Conv2D(64, (3, 3), activation='relu', name='block2_conv1')(x)
x = Conv2D(64, (3, 3), activation='relu', name='block2_conv2')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x)

# Block 3
x = Conv2D(64, (3, 3), activation='relu', name='block3_conv1')(x)
x = Conv2D(64, (3, 3), activation='relu', name='block3_conv2')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x)

# Block 4
x = Conv2D(64, (3, 3), activation='relu', name='block4_conv1')(x)
x = Conv2D(64, (3, 3), activation='relu', name='block4_conv2')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(x)

# Block 5
x = Conv2D(64, (3, 3), activation='relu', name='block5_conv1')(x)
x = Conv2D(64, (3, 3), activation='relu', name='block5_conv2')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(x)

# Classification block
x = Flatten(name='flatten')(x)
x = Dense(1024, activation='relu', name='fc1')(x)
x = Dense(num_classes, activation='softmax', name='pred')(x)

model = Model(input_layer, x)
model.summary()
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc'])