from tensorflow.keras.models import load_model
import os
import pandas as pd
from keras.preprocessing.image import ImageDataGenerator,img_to_array, load_img
import cv2,matplotlib.pyplot as plt,numpy as np
from keras.preprocessing import image
train_datagen = ImageDataGenerator(rescale= 1./255,
shear_range = 0.3,
horizontal_flip=True,
zoom_range = 0.3)
model = load_model('model_fruits.h5')
batch_size = 32
img = load_img("./Test/Apricot/3_100.jpg",target_size=(100,100))
plt.imshow(img)
plt.show()
array_image = img_to_array(img)
array_image = array_image * 1./255
x = np.expand_dims(array_image, axis=0)
images = np.vstack([x])
classes = model.predict_classes(images, batch_size=10)
print(classes)
train_dir = './Training/'
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size= array_image.shape[:2],
batch_size = batch_size,
color_mode= "rgb",
class_mode= "categorical”)
print(train_generator.class_indices)
fig = plt.figure(figsize=(16, 16))
axes = []
files = []
predictions = []
true_labels = []
rows = 5
cols = 2
# 随机选择几个图片
def getRandomImage(path, img_width, img_height):
"""function loads a random image from a random folder in our test path"""
folders = list(filter(lambda x: os.path.isdir(os.path.join(path, x)), os.listdir(path)))
random_directory = np.random.randint(0, len(folders))
path_class = folders[random_directory]
file_path = os.path.join(path, path_class)
file_names = [f for f in os.listdir(file_path) if os.path.isfile(os.path.join(file_path, f))]
random_file_index = np.random.randint(0, len(file_names))
image_name = file_names[random_file_index]
final_path = os.path.join(file_path, image_name)
return image.load_img(final_path, target_size = (img_width, img_height)), final_path, path_class
def draw_test(name, pred, im, true_label):
BLACK = [0, 0, 0]
expanded_image = cv2.copyMakeBorder(im, 160, 0, 0, 300, cv2.BORDER_CONSTANT, value=BLACK)
cv2.putText(expanded_image, "predicted: " + pred, (20, 60), cv2.FONT_HERSHEY_SIMPLEX,
0.85, (255, 0, 0), 2)
cv2.putText(expanded_image, "true: " + true_label, (20, 120), cv2.FONT_HERSHEY_SIMPLEX,
0.85, (0, 255, 0), 2)
return expanded_image
IMG_ROWS, IMG_COLS = 100, 100
# predicting images
for i in range(0, 10):
path = "./Test"
img, final_path, true_label = getRandomImage(path, IMG_ROWS, IMG_COLS)
files.append(final_path)
true_labels.append(true_label)
x = image.img_to_array(img)
x = x * 1./255
x = np.expand_dims(x, axis=0)
images = np.vstack([x])
classes = model.predict_classes(images, batch_size=10)
predictions.append(classes)
class_labels = train_generator.class_indices
class_labels = {v: k for k, v in class_labels.items()}
class_list = list(class_labels.values())
for i in range(0, len(files)):
image = cv2.imread(files[i])
image = draw_test("Prediction", class_labels[predictions[i][0]], image, true_labels[i])
axes.append(fig.add_subplot(rows, cols, i+1))
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.grid(False)
plt.axis('off')
plt.show()