Views
No views yet
1import tensorflow as tf
2from PIL import Image
3import numpy as np
4import os # Added for os.path.join
5
6# Load the model
7# Ensure the model file 'stroke_classification_model.h5' is in the same directory
8# or provide the full path.
9model = tf.keras.models.load_model('stroke_classification_model.h5')
10
11# Define your class names (must match how your model was trained)
12CLASS_NAMES = ['hemorrhagic_stroke', 'ischemic_stroke', 'no_stroke'] # Automatically populated from your Colab session
13
14def preprocess_image_for_prediction(image_path, target_size=(224, 224), pixel_threshold=40):
15 img = Image.open(image_path).convert("L")
16 original_width, original_height = img.size
17 data = np.array(img)
18 rows_with_content = np.any(data > pixel_threshold, axis=1)
19 cols_with_content = np.any(data > pixel_threshold, axis=0)
20 try:
21 min_row = np.where(rows_with_content)[0][0]
22 max_row = np.where(rows_with_content)[0][-1]
23 min_col = np.where(cols_with_content)[0][0]
24 max_col = np.where(cols_with_content)[0][-1]
25 except IndexError:
26 cropped_img = img
27 else:
28 buffer = 5
29 min_row = max(0, min_row - buffer)
30 max_row = min(original_height - 1, max_row + buffer)
31 min_col = max(0, min_col - buffer)
32 max_col = min(original_width - 1, max_col + buffer)
33 cropped_img = img.crop((min_col, min_row, max_col + 1, max_row + 1))
34 processed_img = cropped_img.resize(target_size, Image.LANCZOS)
35 if processed_img.mode == 'L':
36 processed_img = processed_img.convert('RGB')
37 img_array = tf.keras.utils.img_to_array(processed_img)
38 img_array = tf.expand_dims(img_array, 0)
39 return img_array
40
41# Example usage:
42# image_path = "path/to/your/new_mri_image.jpg"
43# preprocessed_img = preprocess_image_for_prediction(image_path)
44# if preprocessed_img is not None:
45# predictions = model.predict(preprocessed_img)
46# predicted_class_index = np.argmax(predictions[0])
47# predicted_class_name = CLASS_NAMES[predicted_class_index]
48# confidence = np.max(predictions[0]) * 100
49# print(f"Predicted: {predicted_class_name} with {confidence:.2f}% confidence")