我训练了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,)
答案 0 :(得分:2)
你可以做这样的事情
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
答案 1 :(得分:1)
您可以在将图像转换为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
。
答案 2 :(得分: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)