automatyczny_kelner/Network/TesterRandom.py

65 lines
2.5 KiB
Python
Raw Normal View History

2023-06-01 23:59:47 +02:00
import os
2023-06-02 12:03:31 +02:00
from pathlib import Path
2023-06-01 23:59:47 +02:00
import numpy as np
2023-06-01 23:51:27 +02:00
import tensorflow as tf
from tensorflow import keras
# Load the trained model
2023-06-02 00:14:50 +02:00
model = keras.models.load_model('Network/trained_model.h5')
2023-06-01 23:51:27 +02:00
# Load the class names
2023-06-02 12:03:31 +02:00
class_names = ['table', 'done', 'order']
2023-06-01 23:51:27 +02:00
# Path to the folder containing test images
2023-06-02 00:14:50 +02:00
test_images_folder = 'Network/Testing/'
2023-06-01 23:51:27 +02:00
# Iterate over the test images
i = 0
errorcount = 0
for folder_name in os.listdir(test_images_folder):
folder_path = os.path.join(test_images_folder, folder_name)
if os.path.isdir(folder_path):
print('Testing images in folder:', folder_name)
2023-06-02 12:03:31 +02:00
2023-06-01 23:51:27 +02:00
# True class based on folder name
if folder_name == 'Empty':
2023-06-02 12:03:31 +02:00
true_class = 'table'
2023-06-01 23:51:27 +02:00
elif folder_name == 'Food':
2023-06-02 12:03:31 +02:00
true_class = 'done'
2023-06-01 23:51:27 +02:00
elif folder_name == 'People':
2023-06-02 12:03:31 +02:00
true_class = 'order'
2023-06-01 23:51:27 +02:00
# Iterate over the files in the subfolder
for filename in os.listdir(folder_path):
if filename.endswith('.jpg') or filename.endswith('.jpeg'):
2023-06-02 12:03:31 +02:00
i += 1
2023-06-01 23:51:27 +02:00
# Load and preprocess the test image
image_path = os.path.join(folder_path, filename)
2023-06-02 12:03:31 +02:00
test_image = keras.preprocessing.image.load_img(
image_path, target_size=(100, 100))
2023-06-02 00:14:50 +02:00
test_image = keras.preprocessing.image.img_to_array(test_image)
2023-06-01 23:51:27 +02:00
test_image = np.expand_dims(test_image, axis=0)
test_image = test_image / 255.0 # Normalize the image
2023-06-02 12:03:31 +02:00
2023-06-01 23:51:27 +02:00
# Reshape the image array to (1, height, width, channels)
2023-06-02 12:03:31 +02:00
test_image = np.reshape(test_image, (1, 100, 100, 3))
2023-06-01 23:51:27 +02:00
# Make predictions
predictions = model.predict(test_image)
predicted_class_index = np.argmax(predictions[0])
predicted_class = class_names[predicted_class_index]
2023-06-02 12:03:31 +02:00
2023-06-02 00:14:50 +02:00
direct = 'Network/Results/'
2023-06-02 12:03:31 +02:00
filename = str(i) + predicted_class + '.jpeg'
2023-06-01 23:51:27 +02:00
test_image = np.reshape(test_image, (100, 100, 3))
2023-06-02 12:03:31 +02:00
Path(direct).mkdir(parents=True, exist_ok=True)
tf.keras.preprocessing.image.save_img(
direct+filename, test_image)
2023-06-01 23:51:27 +02:00
if predicted_class != true_class:
errorcount += 1
print('Image:', filename)
print('True class:', true_class)
print('Predicted class:', predicted_class)
print()
2023-06-02 12:03:31 +02:00
print('Error count: ', errorcount)