【问题标题】:Preprocessing of a single image for prediction. ( CNN build and trained with Keras)对单个图像进行预处理以进行预测。 (CNN 使用 Keras 构建和训练)
【发布时间】:2018-12-15 00:00:57
【问题描述】:

缺乏理解如何使用现有训练模型(keras Sequential.

CNN 的预处理和训练如下所示: 从 keras.preprocessing.image 导入 ImageDataGenerator

train_datagen = ImageDataGenerator(rescale=1./255,
                                   shear_range=0.2,
                                   zoom_range=0.2,
                                   horizontal_flip=True)

test_datagen = ImageDataGenerator(rescale=1./255)

training_set = train_datagen.flow_from_directory('dataset/training_set',
                                                 target_size=(64, 64),
                                                 batch_size=32,
                                                 class_mode='binary')

test_set = test_datagen.flow_from_directory('dataset/test_set',
                                            target_size=(64, 64),
                                            batch_size=32,
                                            class_mode='binary')

classifier.fit_generator(training_set,
                         steps_per_epoch=8000,
                         epochs=25,
                         validation_data=test_set,
                         validation_steps=2000)

由于 predict_generator 没有工作,我卡住了......

【问题讨论】:

  • 你能澄清你的问题吗? “没有工作”是什么意思?
  • 嗨@NicoHaase 是的,它确实给我带来了一个错误,即它不能只根据需要拍摄图像以拥有一个数组(它不存在,只是图像存在)。我知道等待可以将图像作为可使用的源是很愚蠢的,但我仍然这么认为......但后来我找到了一个调整图像大小和形状以进行评估的选项!感谢您的澄清顺便说一句

标签: numpy opencv keras conv-neural-network cv2


【解决方案1】:
import numpy as np
from keras.preprocessing import image

test_image = image.load_img('dataset/single_prediction/cat_or_dog_1.jpg', target_size(64,64))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image,axis=0)
result = classifier.predict(test_image)
training_set.class_indices

【讨论】:

  • 如果您需要进一步的预处理(例如重新缩放),请查看 keras ImageDataGenerator() 实现。很好理解。
  • 缺少一个“=”,我认为:image.load_img(..., target_size = (64,64))
【解决方案2】:

经过一番谷歌搜索后,我发现使用 opencv 预处理单个图像更好,因此转到其文档,通过终端安装在 mac 上(使用 conda)。

conda install opencv

接下来的代码尝试了这个:

import cv2
import numpy as np

predict_datagen = ImageDataGenerator(rescale=1./255)

img1 = cv2.imread('path_to_image/img_1.jpg')
img1 = cv2.resize(img1, (64, 64))

在调整大小后知道模型的图像输入形状为 (64, 64, 3),我检查了形状是否匹配

print(img1.shape)

结果一切都很好,所以我需要添加维度以匹配模型的要求,这是我在收到 ValueError 后发现的:

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

所以图像被重新塑造:

img1 = np.array(img1).reshape((1, 64, 64, 3))#do not miss the order in tuple

之后,我收到了所需形状和大小的图像,并准备好使用predict 方法进行单次预测。

【讨论】:

    猜你喜欢
    • 2017-07-18
    • 1970-01-01
    • 2020-02-04
    • 2018-05-29
    • 1970-01-01
    • 2017-07-07
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多