【问题标题】:How to import a trained model to predict a single image?如何导入经过训练的模型来预测单个图像?
【发布时间】:2018-10-12 04:30:26
【问题描述】:

我通过 Keras 训练了一个 CNN 模型,并通过 model.save('model.h5') 保存了该模型。 但是我想在单个图像上测试我的模型,我不知道如何将自己的图像导入到我的模型中。

# Image generators
train_datagen = ImageDataGenerator(rescale= 1./255)
validation_datagen = ImageDataGenerator(rescale=1./255)

train_generator = train_datagen.flow_from_directory(  
    train_data_dir,
    target_size=(image_size, image_size),
    shuffle=True,
    batch_size=batch_size,
    class_mode='categorical'
    )

validation_generator = validation_datagen.flow_from_directory(
    validation_data_dir,
    target_size=(image_size, image_size),
    batch_size=batch_size,
    shuffle=True,
    class_mode='categorical'
    )

# Fit model
history = model.fit_generator(train_generator,
                steps_per_epoch=(nb_train_samples // batch_size),
                epochs=nb_epoch,
                validation_data=validation_generator,
                callbacks=[early_stopping],# save_best_model],
                validation_steps=(nb_validation_samples // batch_size)
               )

# Save model
model.save_weights('full_model_weights.h5')
model.save('model.h5')

我是 keras 的新手。如何将图像处理给我的模型并将我的图像分类到某个类。

输入的形状:

if K.image_data_format() == 'channels_first':
    input_shape = (3, image_size, image_size)
else:
    input_shape = (image_size, image_size, 3)

我的导入图片代码:

from keras.models import load_model
m=load_model("model.h5")

if K.image_data_format() == 'channels_first':
    input_shape = (3, image_size, image_size)
else:
    input_shape = (image_size, image_size, 3)

cloudy_pic="./Weather/weather_database/cloudy/4152.jpg"
im=Image.open(cloudy_pic).convert('RGB')
data=np.array(im,dtype=np.float32)
data=np.reshape(500, 500,3)
pre=m.predict_classes(data)
pre

还有错误:

AttributeError: 'int' object has no attribute 'reshape'
During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-30-ebc72e185819> in <module>()
     10 im=Image.open(cloudy_pic).convert('RGB')
     11 data=np.array(im,dtype=np.float32)
---> 12 data=np.reshape(500, 500,3)
     13 pre=m.predict_classes(data)
     14 pre

~/anaconda3/envs/tensorflow/lib/python3.6/site- packages/numpy/core/fromnumeric.py in reshape(a, newshape, order)
    230            [5, 6]])
    231     """
--> 232     return _wrapfunc(a, 'reshape', newshape, order=order)
    233 
    234 

~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/numpy/core/fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)
     65     # a downstream library like 'pandas'.
     66     except (AttributeError, TypeError):
---> 67         return _wrapit(obj, method, *args, **kwds)
     68 
     69 

~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/numpy/core/fromnumeric.py in _wrapit(obj, method, *args, **kwds)
     45     except AttributeError:
     46         wrap = None
---> 47     result = getattr(asarray(obj), method)(*args, **kwds)
     48     if wrap:
     49         if not isinstance(result, mu.ndarray):

ValueError: cannot reshape array of size 1 into shape (500,)

【问题讨论】:

    标签: python tensorflow machine-learning deep-learning keras


    【解决方案1】:
    # code for predicting an image stored locally against a trained model
    # my local image is 28 x 28 already
    import numpy as np
    from PIL import Image
    from keras.preprocessing import image
    img = image.load_img('file path include full file name')# , target_size=(32,32))
    img  = image.img_to_array(img)
    img  = img.reshape((1,) + img.shape)
    # img  = img/255
    img = img.reshape(-1,784)
    img_class=model.predict_classes(img) 
    # this model above was already trained 
    # code from https://machinelearningmastery.com/handwritten-digit-recognition-using-convolutional-#neural-networks-python-keras/
    prediction = img_class[0]
    classname = img_class[0]
    print("Class: ",classname)
    

    【讨论】:

      【解决方案2】:

      您可以在将图像转换为 np 数组之前调整其大小。

      img = Image.open(img_path)
      img = img.resize((image_size,image_size))
      img = np.array(img)
      img = img / 255.0
      img = img.reshape(1,image_size,image_size,3)
      m.predict_classes(img)
      

      模型的输入形状必须是[None,image_size,image_size,3],如果channels_first,则为[None,3,image_size,image_size]

      【讨论】:

      • 但是当我这样做时,发生了错误。代码在那里:paste.ubuntu.com/p/kkTWdn87hv
      • 您需要将图像大小调整为(image_size,image_size),然后再对其进行整形。
      • 我看到错误信息是“ValueError: cannot reshape array of size 1440000 into shape (1,3,500,500)”,3*500*500 =750000,如果你已经调整了它的大小,数组不会是 1440000,应该是 750000,而且我没有看到您在代码中调整图像大小。
      • 非常抱歉...谢谢~我的原始数据集的大小尚未调整。我的新数据集的大小已调整大小。在此示例中,我导入了原始数据集的图像。对不起...
      【解决方案3】:

      你可以这样做

      model = load_model('model.h5')
      img=#YOUR IMAGE (Let's say it's 32,32,1)
      image_x = 32
      image_y = 32
      img = cv2.resize(img, (image_x, image_y))
      img = np.array(img, dtype=np.float32)
      img = np.reshape(img, (-1, image_x, image_y, 1))
      pred_probab = model.predict(img)[0]
      pred_class = list(pred_probab).index(max(pred_probab))
      return max(pred_probab), pred_class
      

      【讨论】:

      • 但是不知道import的形状
      • 尝试根据你的模型重塑它
      • ValueError: 无法将大小为 1440000 的数组重塑为形状 (1,3,500,500)
      • 你的图片尺寸是多少。 (像素大小)
      • 我所有的图片:500x500
      猜你喜欢
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-24
      • 2022-01-21
      • 2019-03-24
      • 2020-07-04
      相关资源
      最近更新 更多