Brain tumor
classification + segmentation model trained on MRI scans.
Part of the
WellScan Healthcare project — BTech Final Year Project
Built on U-Net with ResNet skip connections and attention gates integrated into the decoder path.
1from huggingface_hub import hf_hub_download
2from keras.models import load_model
3import tensorflow as tf
4
5threshold = 0.38
6
7def mean_iou(y_true, y_pred):
8 y_true = tf.cast(y_true, tf.float32)
9 y_pred = tf.cast(y_pred >= threshold, tf.float32)
10 intersection = tf.reduce_sum(tf.abs(y_true * y_pred))
11 union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) - intersection
12 return intersection / union
13
14def dice_coefficient(y_true, y_pred, smooth=1e-5):
15 y_true = tf.cast(y_true, tf.float32)
16 y_pred = tf.cast(y_pred >= threshold, tf.float32)
17 intersection = tf.reduce_sum(y_true * y_pred)
18 union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred)
19 return (2. * intersection + smooth) / (union + smooth)
20
21# Download model from Hugging Face
22model_path = hf_hub_download(
23 repo_id="varad-patil/wellscanhealthcare-brain-tumor",
24 filename="AT_RESu_net_all_STD_0.0927_th=0.38.hdf5"
25)
26
27# Load with custom metrics
28model = load_model(model_path, custom_objects={
29 'mean_iou': mean_iou,
30 'dice_coefficient': dice_coefficient
31})
1import cv2
2import numpy as np
3
4def preprocess(image_path, size=224):
5 img = cv2.imread(image_path)
6 img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
7 _, binary = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
8 contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
9 contours = sorted(contours, key=cv2.contourArea, reverse=True)[0]
10 x, y, w, h = cv2.boundingRect(contours)
11 img = cv2.resize(img[y:y+h, x:x+w], (size, size))
12 img = (img - img.mean()) / img.std()
13 return np.expand_dims(np.expand_dims(img, axis=-1), axis=0)
14
15class_labels = ['meningioma', 'glioma', 'pituitary tumor', 'noTumor']
16
17img = preprocess("your_mri_scan.jpg")
18classification, segmentation_mask = model.predict(img)
19
20predicted_class = class_labels[np.argmax(classification)]
21confidence = np.max(classification) * 100
22print(f"Prediction: {predicted_class} ({confidence:.2f}%)")