# Import necessary libraries
from tkinter import messagebox
from tkinter import *
from tkinter import simpledialog
import tkinter
from tkinter import filedialog
import [Link] as plt
import numpy as np
from [Link] import askopenfilename
import os
import cv2
from sklearn.model_selection import train_test_split
from [Link] import accuracy_score
import imutils
from [Link] import to_categorical
from [Link] import MaxPooling2D
from [Link] import Dense, Dropout, Activation, Flatten
from [Link] import Convolution2D
from [Link] import Sequential
from [Link] import model_from_json
import pickle
from sklearn import metrics
import ftplib
from tkinter import ttk
# Initialize the main Tkinter window
main = [Link]()
[Link]("Identifying Brain Tumor using X-Ray Images") # Designing main
screen
[Link]("1300x1200")
# Global variables
global filename
global accuracy
X = [] # To store image data
Y = [] # To store labels
global classifier
disease = ['No Tumor Detected', 'Tumor Detected'] # Class labels
# Load the pre-trained segmentation model
with open('Model/segmented_model.json', "r") as json_file:
loaded_model_json = json_file.read()
segmented_model = model_from_json(loaded_model_json)
json_file.close()
segmented_model.load_weights("Model/segmented_weights.h5")
# Function to perform edge detection on the segmented image
def edgeDetection():
img = [Link]('[Link]') # Load the segmented image
orig = [Link]('[Link]') # Load the original image
gray = [Link](img, cv2.COLOR_BGR2GRAY) # Convert to grayscale
thresh = [Link](gray, 30, 255, cv2.THRESH_BINARY)[1] # Apply
binary thresholding
contours = [Link](thresh, cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE) # Find contours
contours = contours[0] if len(contours) == 2 else contours[1]
min_area = 0.95 * 180 * 35 # Define minimum area for tumor
max_area = 1.05 * 180 * 35 # Define maximum area for tumor
result = [Link]() # Copy the original image
for c in contours:
area = [Link](c) # Calculate contour area
[Link](result, [c], -1, (0, 0, 255), 10) # Draw
contours
if area > min_area and area < max_area:
[Link](result, [c], -1, (0, 255, 255), 10) #
Highlight tumor area
return result
# Function to segment the tumor from the input image
def tumorSegmentation(filename):
global segmented_model
img = [Link](filename, 0) # Read the image in grayscale
img = [Link](img, (64, 64), interpolation=cv2.INTER_CUBIC) #
Resize the image
img = [Link](1, 64, 64, 1) # Reshape for model input
img = (img - 127.0) / 127.0 # Normalize the image
preds = segmented_model.predict(img) # Predict the tumor segmentation
preds = preds[0]
print([Link])
orig = [Link](filename, 0) # Read the original image
orig = [Link](orig, (300, 300), interpolation=cv2.INTER_CUBIC) #
Resize the original image
[Link]("[Link]", orig) # Save the resized original image
segmented_image = [Link](preds, (300, 300),
interpolation=cv2.INTER_CUBIC) # Resize the segmented image
[Link]("[Link]", segmented_image * 255) # Save the segmented
image
edge_detection = edgeDetection() # Perform edge detection
return segmented_image * 255, edge_detection # Return the segmented
and edge-detected images
# Function to upload the dataset
def uploadDataset():
global filename
filename = [Link](initialdir=".") # Open a dialog to
select the dataset directory
[Link]('1.0', END) # Clear the text box
[Link](END, filename + " loaded\n") # Display the selected
directory
# Function to preprocess the dataset and extract features
def datasetPreprocessing():
global X, Y
[Link]()
[Link]()
if [Link]('Model/myimg_data.[Link]'): # Check if
preprocessed data exists
X = [Link]('Model/myimg_data.[Link]') # Load preprocessed data
Y = [Link]('Model/myimg_label.[Link]') # Load labels
else:
# Process images from the "no tumor" directory
for root, dirs, directory in [Link](filename + "/no"):
for i in range(len(directory)):
name = directory[i]
img = [Link](filename + "/no/" + name, 0) # Read the
image
ret2, th2 = [Link](img, 0, 255, cv2.THRESH_BINARY +
cv2.THRESH_OTSU) # Apply Otsu's thresholding
img = [Link](img, (128, 128)) # Resize the image
im2arr = [Link](img) # Convert to numpy array
im2arr = [Link](128, 128, 1) # Reshape for model
input
[Link](im2arr) # Append to the dataset
[Link](0) # Label for "no tumor"
print(filename + "/no/" + name)
# Process images from the "tumor" directory
for root, dirs, directory in [Link](filename + "/yes"):
for i in range(len(directory)):
name = directory[i]
img = [Link](filename + "/yes/" + name, 0)
ret2, th2 = [Link](img, 0, 255, cv2.THRESH_BINARY +
cv2.THRESH_OTSU)
img = [Link](img, (128, 128))
im2arr = [Link](img)
im2arr = [Link](128, 128, 1)
[Link](im2arr)
[Link](1) # Label for "tumor"
print(filename + "/yes/" + name)
X = [Link](X) # Convert to numpy array
Y = [Link](Y)
[Link]("Model/myimg_data.txt", X) # Save the preprocessed data
[Link]("Model/myimg_label.txt", Y) # Save the labels
print([Link])
print([Link])
print(Y)
[Link]('ss', X[20]) # Display a sample image
[Link](0)
[Link](END, "Total number of images found in dataset: " +
str(len(X)) + "\n")
[Link](END, "Total number of classes: " + str(len(set(Y))) +
"\n\n")
[Link](END, "Class labels found in dataset: " + str(disease))
# Function to train the CNN model for tumor detection
def trainTumorDetectionModel():
global accuracy, classifier
YY = to_categorical(Y) # Convert labels to categorical format
indices = [Link]([Link][0])
[Link](indices) # Shuffle the dataset
x_train = X[indices]
y_train = YY[indices]
if [Link]('Model/[Link]'): # Check if a pre-trained model
exists
with open('Model/[Link]', "r") as json_file:
loaded_model_json = json_file.read()
classifier = model_from_json(loaded_model_json) # Load the
model
classifier.load_weights("Model/model_weights.h5") # Load the
weights
else:
# Split the dataset into training and testing sets
X_trains, X_tests, y_trains, y_tests = train_test_split(x_train,
y_train, test_size=0.2, random_state=0)
classifier = Sequential() # Initialize the CNN model
[Link](Convolution2D(32, 3, 3, input_shape=(128, 128, 1),
activation='relu')) # Add convolutional layer
[Link](MaxPooling2D(pool_size=(2, 2))) # Add max-pooling
layer
[Link](Convolution2D(32, 3, 3, activation='relu')) # Add
another convolutional layer
[Link](MaxPooling2D(pool_size=(2, 2))) # Add another
max-pooling layer
[Link](Flatten()) # Flatten the output
[Link](Dense(output_dim=128, activation='relu')) # Add a
fully connected layer
[Link](Dense(output_dim=2, activation='softmax')) # Add
the output layer
print([Link]()) # Print the model summary
[Link](optimizer='adam',
loss='categorical_crossentropy', metrics=['accuracy']) # Compile the
model
hist = [Link](x_train, y_train, batch_size=16, epochs=10,
validation_split=0.2, shuffle=True, verbose=2) # Train the model
classifier.save_weights('Model/model_weights.h5') # Save the
model weights
model_json = classifier.to_json() # Save the model architecture
with open("Model/[Link]", "w") as json_file:
json_file.write(model_json)
f = open('Model/[Link]', 'wb') # Save the training history
[Link]([Link], f)
[Link]()
f = open('Model/[Link]', 'rb') # Load the training history
data = [Link](f)
[Link]()
acc = data['accuracy']
accuracy = acc[4] * 100 # Calculate accuracy
[Link](END, '\n\nCNN Brain Tumor Model Generated. See black
console to view layers of CNN\n\n')
[Link](END, "CNN Brain Tumor Prediction Accuracy on Test Images:
" + str(accuracy) + "\n")
# Function to classify an input image and detect tumors
def tumorClassification():
filename = [Link](initialdir="testImages") # Open
a dialog to select an image
img = [Link](filename, 0) # Read the image
img = [Link](img, (128, 128)) # Resize the image
im2arr = [Link](img) # Convert to numpy array
im2arr = [Link](1, 128, 128, 1) # Reshape for model input
XX = [Link](im2arr)
predicts = [Link](XX) # Predict the class
print(predicts)
cls = [Link](predicts) # Get the predicted class
print(cls)
if cls == 0: # If no tumor is detected
img = [Link](filename)
img = [Link](img, (800, 500))
[Link](img, 'Classification Result: ' + disease[cls], (10,
25), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 255), 2)
[Link]('Classification Result: ' + disease[cls], img)
[Link](0)
if cls == 1: # If a tumor is detected
segmented_image, edge_image = tumorSegmentation(filename) #
Segment the tumor
img = [Link](filename)
img = [Link](img, (800, 500))
[Link](img, 'Classification Result: ' + disease[cls], (10,
25), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 255), 2)
[Link]('Classification Result: ' + disease[cls], img)
[Link]("Tumor Segmented Image", segmented_image)
[Link]("Edge Detected Image", edge_image)
[Link](0)
# Function to plot the training accuracy and loss graph
def graph():
f = open('Model/[Link]', 'rb') # Load the training history
data = [Link](f)
[Link]()
accuracy = data['accuracy']
loss = data['loss']
[Link](figsize=(10, 6))
[Link](True)
[Link]('Training Epoch')
[Link]('Accuracy/Loss')
[Link](loss, 'ro-', color='red') # Plot the loss
[Link](accuracy, 'ro-', color='green') # Plot the accuracy
[Link](['Loss', 'Accuracy'], loc='upper left')
[Link]('Brain Tumor CNN Model Training Accuracy & Loss Graph')
[Link]()
# GUI Design
font = ('times', 16, 'bold')
title = Label(main, text='Identifying Brain Tumor using X-Ray Images')
[Link](bg='darkviolet', fg='gold')
[Link](font=font)
[Link](height=3, width=120)
[Link](x=0, y=5)
font1 = ('times', 12, 'bold')
text = Text(main, height=20, width=150)
scroll = Scrollbar(text)
[Link](yscrollcommand=[Link])
[Link](x=50, y=120)
[Link](font=font1)
# Buttons for various functionalities
uploadButton = Button(main, text="Upload Tumor X-Ray Images Dataset",
command=uploadDataset)
[Link](x=50, y=550)
[Link](font=font1)
preprocessButton = Button(main, text="Dataset Preprocessing & Features
Extraction", command=datasetPreprocessing)
[Link](x=430, y=550)
[Link](font=font1)
cnnButton = Button(main, text="Trained CNN Brain Tumor Detection Model",
command=trainTumorDetectionModel)
[Link](x=810, y=550)
[Link](font=font1)
classifyButton = Button(main, text="Brain Tumor Segmentation &
Classification", command=tumorClassification)
[Link](x=50, y=600)
[Link](font=font1)
graphButton = Button(main, text="Training Accuracy Graph", command=graph)
[Link](x=430, y=600)
[Link](font=font1)
[Link](bg='turquoise')
[Link]()