import tensorflow as tf import numpy as np from tensorflow.keras import backend as K from adabelief_tf import AdaBeliefOptimizer import matplotlib.pyplot as plt import os from glob import glob # [Previous function definitions stay the same: iou_coef, dice_coef, etc.] def visualize_prediction(original_img, mask_pred, tags_pred, save_path=None): plt.figure(figsize=(15, 5)) # Original image plt.subplot(1, 3, 1) plt.imshow(original_img[:,:,0], cmap='gray') plt.title('Original Image') plt.axis('off') # Predicted mask plt.subplot(1, 3, 2) plt.imshow(mask_pred[:,:,0], cmap='jet') plt.title('Predicted Mask') plt.axis('off') # Overlay plt.subplot(1, 3, 3) plt.imshow(original_img[:,:,0], cmap='gray') plt.imshow(mask_pred[:,:,0], cmap='jet', alpha=0.4) plt.title(f'Overlay\nEye: {tags_pred[0]:.3f}, Blink: {tags_pred[1]:.3f}') plt.axis('off') plt.tight_layout() if save_path: plt.savefig(save_path) plt.close() else: plt.show() def test_single_image(image_path, model, output_dir=None): print(f"\nTesting image: {os.path.basename(image_path)}") img = load_image(image_path) img_batch = tf.expand_dims(img, 0) # Get predictions mask_pred, tags_pred = model.predict(img_batch, verbose=0) print("Predictions:") print(f"Eye detection confidence: {tags_pred[0][0]:.3f}") print(f"Blink detection confidence: {tags_pred[0][1]:.3f}") # Visualize if output directory is provided if output_dir: base_name = os.path.splitext(os.path.basename(image_path))[0] save_path = os.path.join(output_dir, f'{base_name}_prediction.png') visualize_prediction(img.numpy(), mask_pred[0], tags_pred[0], save_path) return mask_pred[0], tags_pred[0] # Load the model model_path = 'runs/b32_c-conv_d-|root|meye|data|NN_human_mouse_eyes|_g1.5_l0.001_num_c1_num_f16_num_s5_r128_se23_sp-random_up-relu_us0/best_model.h5' print("Loading model...") model = tf.keras.models.load_model(model_path, custom_objects=custom_objects) output_dir = "/root/meye/test_predictions" # absolute path in /meye directory os.makedirs(output_dir, exist_ok=True) print(f"\nSaving predictions to: {output_dir}") # Test directory with multiple images test_dir = "/root/meye/data/NN_human_mouse_eyes/fullFrames" image_files = glob(os.path.join(test_dir, "*.jpg"))[:10] # Test first 10 images print(f"\nTesting {len(image_files)} images...") results = [] for image_path in image_files: mask_pred, tags_pred = test_single_image(image_path, model, output_dir) results.append({ 'image': os.path.basename(image_path), 'eye_conf': tags_pred[0], 'blink_conf': tags_pred[1] }) # Print summary print("\nSummary:") df = pd.DataFrame(results) print("\nAverage confidences:") print(f"Eye detection: {df['eye_conf'].mean():.3f} ± {df['eye_conf'].std():.3f}") print(f"Blink detection: {df['blink_conf'].mean():.3f} ± {df['blink_conf'].std():.3f}")