-
Notifications
You must be signed in to change notification settings - Fork 3
/
brain_tumour_detection_using_mri_scans.py
225 lines (183 loc) · 6.55 KB
/
brain_tumour_detection_using_mri_scans.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# -*- coding: utf-8 -*-
"""Brain Tumour Detection using MRI scans.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1_dCplLvBUVGjB-xP0J2O13hLY-PIYGFW
"""
# import data from drive
from google.colab import drive
drive.mount('/content/gdrive')
!unzip -q "/content/gdrive/My Drive/Brain_Tumour_MRI_Data.zip"
!unzip -q "/content/gdrive/My Drive/Brain_model.h5.zip"
'''
project : Covid-19-detection-using-Xray
Author : @kanishksh4rma
'''
from imutils import paths
import matplotlib.pyplot as plt
import argparse
import os
from keras.preprocessing.image import ImageDataGenerator
from keras.applications import VGG16
from keras.layers import AveragePooling2D, Dropout,Flatten,Dense,Input
from keras.models import Model
from keras.optimizers import Adam
from keras.utils import to_categorical
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
dataset = "/content/Brain_Tumour_MRI_Data" # path to the dataset
args={}
args["dataset"]=dataset
import numpy as np
import cv2
img_paths = list(paths.list_images(args["dataset"])) #image paths
data = []
labels = []
for path in img_paths:
label = path.split(os.path.sep)[-2] #split the image paths
image = cv2.imread(path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) #Convert images into RGB Channel
# Though it isnt necessary for X-ray images
image = cv2.resize(image, (224, 224)) #Resizing the images
data.append(image)
labels.append(label)
data = np.array(data) / 255.0
labels = np.array(labels)
sum=0
for i in data:
sum += 1
print(sum)
Data_Dir = "/content/Brain_Tumour_MRI_Data/"
Cimages = os.listdir(Data_Dir+"Tumour")
Nimages = os.listdir(Data_Dir+"Normal")
import matplotlib.pyplot as plt
import cv2
import skimage
from skimage.transform import resize
import numpy as np
# plot some of the X-rays
def plotter(i):
normal = cv2.imread(Data_Dir+"Normal//"+Nimages[i])
normal = skimage.transform.resize(normal, (150, 150, 3))
coronavirus = cv2.imread(Data_Dir+"Tumour//"+Cimages[i])
coronavirus = skimage.transform.resize(coronavirus, (150, 150, 3) , mode = 'reflect')
pair = np.concatenate((normal, coronavirus), axis=1)
print("Normal Brain MRI Vs Tumour")
plt.figure(figsize=(10,5))
plt.imshow(pair)
plt.show()
for i in range(0,5):
plotter(i)
LB = LabelBinarizer()
#Initialize label binarizer
labels = LB.fit_transform(labels)
labels = to_categorical(labels)
# test train split
(X_train, X_test, Y_train, Y_test) = train_test_split(data, labels,
test_size=0.20, stratify=labels, random_state=42)
#rotate images to create more data
trainAug = ImageDataGenerator(
rotation_range=15,
fill_mode="nearest")
bModel = VGG16(weights="imagenet", include_top=False,input_tensor=Input(shape=(224, 224, 3))) #base_Model
hModel = bModel.output #head_Model
hModel = AveragePooling2D(pool_size=(4, 4))(hModel)
hModel = Flatten(name="flatten")(hModel)
hModel = Dense(64, activation="relu")(hModel)
hModel = Dropout(0.5)(hModel)
hModel = Dense(2, activation="softmax")(hModel)
model = Model(inputs=bModel.input, outputs=hModel)
for layer in bModel.layers:
layer.trainable = False
X_train.shape,X_test.shape,Y_train.shape,Y_test.shape
INIT_LR = 1e-3
EPOCHS = 10
BS = 8
opt = Adam(lr=INIT_LR, decay=INIT_LR / EPOCHS)
model.compile(loss="binary_crossentropy", optimizer=opt,metrics=["accuracy"])
R = model.fit_generator(
trainAug.flow(X_train, Y_train, batch_size=BS),
steps_per_epoch=len(X_train) // BS,
validation_data=(X_test, Y_test),
validation_steps=len(X_test) // BS,
epochs=EPOCHS)
# Let's test on some random test data
L = 6
W = 5
fig, axes = plt.subplots(L, W, figsize = (12, 12))
axes = axes.ravel()
y_pred = model.predict(X_test, batch_size=BS)
for i in np.arange(0,L*W):
axes[i].imshow(X_test[i])
axes[i].set_title('Prediction = {}\n True = {}'.format(y_pred.argmax(axis=1)[i], Y_test.argmax(axis=1)[i]))
axes[i].axis('off')
plt.subplots_adjust(wspace = 0.5, hspace=0.5)
"""Wow! All every prediction are correct."""
from sklearn.metrics import classification_report
y_pred = model.predict(X_test, batch_size=BS)
y_pred = np.argmax(y_pred, axis=1)
print(classification_report(Y_test.argmax(axis=1), y_pred,target_names=LB.classes_))
from sklearn.metrics import accuracy_score
print('Accuracy score : ',accuracy_score(Y_test.argmax(axis=1),y_pred)*100,'%')
from sklearn.metrics import confusion_matrix
# check for Sensitivity & Specificity
cm = confusion_matrix(Y_test.argmax(axis=1), y_pred)
sensitivity = cm[0, 0] / (cm[0, 0] + cm[0, 1])
specificity = cm[1, 1] / (cm[1, 0] + cm[1, 1])
print('Confusion Matrice : ')
print(cm)
print('-----------------------------')
print("sensitivity: {:.4f}".format(sensitivity))
print("specificity: {:.4f}".format(specificity))
# plot the loss
plt.plot(R.history['loss'], label='train loss')
plt.plot(R.history['val_loss'], label='val loss')
plt.legend()
plt.show()
plt.savefig('LossVal_loss')
# plot the accuracy
plt.plot(R.history['accuracy'], label='train acc')
plt.plot(R.history['val_accuracy'], label='val acc')
plt.legend()
plt.show()
plt.savefig('LossVal_acc')
model.save('Brain_model.h5')
from flask import jsonify
from keras.preprocessing import image
from keras.models import load_model
print('making model ')
from google.colab import files
image1 = files.upload()
image_list = list(image1.keys())
image1 = image_list[0]
print('Image : ',image1)
print('=========================')
print('File uploaded successfully!!!')
print('=========================')
import numpy as np
from flask import jsonify
from keras.preprocessing import image
from keras.models import load_model
print('fetching results...')
new_model = load_model('/content/Brain_model.h5')
test_image = image.load_img(image1,target_size=(224,224))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = new_model.predict(test_image)
print('Results : ',result)
y_pred = np.argmax(result, axis=1)
print('Model prediction: ',result)
#if result[0][0]<result[0][1] and result[0][0]>4.226988e-15:
#if result[0][0]>=1.0 and result[0][1]>=1.8687282e-25 or result[0][1]>=1.0 and result[0][0]>=1.8687282e-25:
if result[0][0]==1.0 and result[0][1]==0 :#or result[0][1]==1.0 and result[0][0]==0:
prediction = "Please upload MRIs only"
elif y_pred == 1:
prediction = 'Patient has Tumour'
#return 1
else:
prediction = 'Patient is Healthy'
#return 0
print('YPred',y_pred)
print('===================================')
print(prediction)
print('===================================')