在CNN模型中的图像上使用预测方法时的尺寸误差 [英] Dimension error when using predict method on an image in a CNN model

查看:99
本文介绍了在CNN模型中的图像上使用预测方法时的尺寸误差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Keras(2.2.4)和TensorFlow(1.9.0)作为后端在单个图像上进行预测:

I am trying to predict on a single image using Keras (2.2.4) and TensorFlow (1.9.0) as the backend:

def enigne(data):

    img=data
    image_shape=img.shape

    num_train_samples = 4206
    num_val_samples = 916
    train_batch_size = 10
    val_batch_size = 10
    IMAGE_SIZE = 64
    IMAGE_CHANNELS = 3
    kernel_size = (3, 3)
    pool_size = (2, 2)
    first_filters = 32
    second_filters = 128
    image_resize=cv.resize(img,(64,64))

    # Loading the model
    model = Sequential()
    model.add(Conv2D(first_filters, kernel_size, activation='relu', input_shape=(64, 64, 3)))
    model.add(Conv2D(first_filters, kernel_size, activation='relu', kernel_regularizer=regularizers.l2(0.001))
    model.add(Conv2D(second_filters, kernel_size, activation='relu', kernel_regularizer=regularizers.l2(0.001)))
    model.add(MaxPooling2D(pool_size=pool_size))
    model.add(Dropout(dropout_conv))
    model.add(Flatten())
    model.add(Dense(256, activation="relu"))
    model.add(Dense(1, activation="sigmoid"))
    model.compile(Adam(lr=0.0001), loss='binary_crossentropy',
                  metrics=['accuracy'])
    datagen = ImageDataGenerator(rescale=1.0 / 255)
    model.load_weights('stableweights.h5')
    y_pred_keras = model.predict_proba(image_resize)
    p = []

    for i in y_pred_keras:
        for k in i:
            if k <= 0.421:
                p.append(0)
            else:
                p.append(1)

    return p

我遇到这样的错误:

ValueError: Error when checking input: expected conv2d_input to have 4 dimensions, but got array with shape (64, 64, 3) 

如何转换为具有适当尺寸的图像以将其输入到Keras模型中?

How can I convert to the image to have proper dimensions to feed it into the Keras model?

推荐答案

Keras模型希望将一批样本作为输入.因此,您需要将第一个轴作为批处理轴:

Keras models expect batch of samples as input. Therefore, you need to have the first axis as the batch axis:

import numpy as np

image_resize = np.expand_dims(image_resize, axis=0)  # shape would be: (1, 64, 64, 3)

这篇关于在CNN模型中的图像上使用预测方法时的尺寸误差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆