Keras load model and predict
Load model and predict with Keras.
- 1. Laden des Modelles
- 2. Datenvorverarbeitung gemäß den Trainingsdaten
- 3. Modellvorhersage und Ergebnisdarstellung
- References
import numpy as np
import argparse
import os
import tensorflow as tf
import glob
import matplotlib.pyplot as plt
import cv2
import random
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", type=str, default = "/home/imagda/sims-data/malaria", help="path dataset of input images")
ap.add_argument("-m", "--model", type=str, default = "orig/saved_model.model", help="path to trained model")
ap.add_argument("-p", "--plot", type=str, default="plot.png", help="path to output loss/accuracy plot")
args = vars(ap.parse_args([]))
model = tf.keras.models.load_model(args["model"])
tot_test_paths = glob.glob(os.path.sep.join([args["dataset"], "test", "*", "*"]))
random.shuffle(tot_test_paths)
print(len(tot_test_paths))
test_images = tot_test_paths[:10]
# initialize a list where to put the new images with label
res_imgs = []
for i, image in enumerate (tot_test_paths[:5]):
# load input image
orig = cv2.imread(image)
# convert from cv2 default BGR --> RGB
img = cv2.cvtColor(orig, cv2.COLOR_BGR2RGB)
# resize image to size accepted by model
img = cv2.resize(img, (64,64))
# rescale image between 0 - 1 floats (previously was at 0- 255 integer)
img = img.astype("float")/255.
# converts a pil image to array
img = tf.keras.preprocessing.image.img_to_array(img)
# img array will get an additional dimension fro batch img(batch=1, R, G, B, 3)
img = np.expand_dims(img, axis=0)
# using preterained model make a prediction
res = model.predict(img)
# max prediction index
pred = res.argmax(axis=1)[0]
label = "Parasitized" if pred == 0 else "Uninfected"
color = (0,0, 255) if pred == 0 else (0,255, 0)
orig = cv2.resize(orig, (128,128))
cv2.putText(orig, label, (3, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
res_imgs.append(orig)
plt.imshow(res_imgs[0])
References
Adrian Rosebrock, OpenCV Face Recognition, PyImageSearch, https://www.pyimagesearch.com/, accessed on 3 January, 2021> www:https://www.pyimagesearch.com/2018/12/10/keras-save-and-load-your-deep-learning-models/