簡體   English   中英

如何導入經過訓練的模型來預測單個圖像?

[英]How to import a trained model to predict a single image?

我通過 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,)

您可以在將圖像轉換為 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][None,3,image_size,image_size]如果channels_first

你可以做這樣的事情

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
# 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM