Keras:单个图像的model.predict [英] Keras: model.predict for a single image

查看:752
本文介绍了Keras:单个图像的model.predict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用Keras预测一张图像。我已经训练好了模型,所以我只是在加载重量。

I'd like to make a prediction for a single image with Keras. I've trained my model so I'm just loading the weights.

from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K
import numpy as np
import cv2

# dimensions of our images.
img_width, img_height = 150, 150



def create_model():
  if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
  else:
    input_shape = (img_width, img_height, 3)

  model = Sequential()
  model.add(Conv2D(32, (3, 3), input_shape=input_shape))
  model.add(Activation('relu'))
  model.add(MaxPooling2D(pool_size=(2, 2)))

  model.add(Conv2D(32, (3, 3)))
  model.add(Activation('relu'))
  model.add(MaxPooling2D(pool_size=(2, 2)))

  model.add(Conv2D(64, (3, 3)))
  model.add(Activation('relu'))
  model.add(MaxPooling2D(pool_size=(2, 2)))

  model.add(Flatten())
  model.add(Dense(64))
  model.add(Activation('relu'))
  model.add(Dropout(0.5))
  model.add(Dense(1))
  model.add(Activation('sigmoid'))

  return model


img = cv2.imread('./test1/1.jpg')
model = create_model()
model.load_weights('./weight.h5')
model.predict(img)

I 'm使用以下方式加载图像:

I'm loading the image using:

img = cv2.imread('./test1/1.jpg')

并使用模型的预测函数:

And using the predict function of the model:

 model.predict(img)

但是我得到了错误:

ValueError: Error when checking : expected conv2d_1_input to have 4 dimensions, but got array with shape (499, 381, 3)

我应该如何对单个图像进行预测?

How should I proceed to have predictions on a single image ?

推荐答案

由于您是在小型批次上训练模型,因此输入的形状为张量 [batch_size,image_width,image_height,number_of_channels]

Since you trained your model on mini-batches, your input is a tensor of shape [batch_size, image_width, image_height, number_of_channels].

预测时,即使只有一张图像,也必须尊重这种形状。您的输入应具有以下形状: [1,image_width,image_height,number_of_channels]

When predicting, you have to respect this shape even if you have only one image. Your input should be of shape: [1, image_width, image_height, number_of_channels].

您可以在容易麻木。假设您有一张5x5x3的图片:

You can do this in numpy easily. Let's say you have a single 5x5x3 image:

    >>> x = np.random.randint(0,10,(5,5,3))
    >>> x.shape
    >>> (5, 5, 3)
    >>> x = np.expand_dims(x, axis=0)
    >>> x.shape
    >>> (1, 5, 5, 3)

现在x是4级张量!

这篇关于Keras:单个图像的model.predict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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