0% found this document useful (0 votes)
2 views

code

This document outlines a Python program using Tkinter and Keras for identifying brain tumors in X-ray images. It includes functionalities for uploading datasets, preprocessing images, training a CNN model for tumor detection, and classifying new images. The program also features graphical visualization of training accuracy and loss, along with edge detection and tumor segmentation capabilities.

Uploaded by

rylegand
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

code

This document outlines a Python program using Tkinter and Keras for identifying brain tumors in X-ray images. It includes functionalities for uploading datasets, preprocessing images, training a CNN model for tumor detection, and classifying new images. The program also features graphical visualization of training accuracy and loss, along with edge detection and tumor segmentation capabilities.

Uploaded by

rylegand
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

# Import necessary libraries

from tkinter import messagebox


from tkinter import *
from tkinter import simpledialog
import tkinter
from tkinter import filedialog
import matplotlib.pyplot as plt
import numpy as np
from tkinter.filedialog import askopenfilename
import os
import cv2
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import imutils
from keras.utils import to_categorical
from keras.layers import MaxPooling2D
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D
from keras.models import Sequential
from keras.models import model_from_json
import pickle
from sklearn import metrics
import ftplib
from tkinter import ttk

# Initialize the main Tkinter window


main = tkinter.Tk()
main.title("Identifying Brain Tumor using X-Ray Images") # Designing main
screen
main.geometry("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 = cv2.imread('myimg.png') # Load the segmented image
orig = cv2.imread('test1.png') # Load the original image
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Convert to grayscale
thresh = cv2.threshold(gray, 30, 255, cv2.THRESH_BINARY)[1] # Apply
binary thresholding
contours = cv2.findContours(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 = orig.copy() # Copy the original image
for c in contours:
area = cv2.contourArea(c) # Calculate contour area
cv2.drawContours(result, [c], -1, (0, 0, 255), 10) # Draw
contours
if area > min_area and area < max_area:
cv2.drawContours(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 = cv2.imread(filename, 0) # Read the image in grayscale
img = cv2.resize(img, (64, 64), interpolation=cv2.INTER_CUBIC) #
Resize the image
img = img.reshape(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(preds.shape)
orig = cv2.imread(filename, 0) # Read the original image
orig = cv2.resize(orig, (300, 300), interpolation=cv2.INTER_CUBIC) #
Resize the original image
cv2.imwrite("test1.png", orig) # Save the resized original image
segmented_image = cv2.resize(preds, (300, 300),
interpolation=cv2.INTER_CUBIC) # Resize the segmented image
cv2.imwrite("myimg.png", 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 = filedialog.askdirectory(initialdir=".") # Open a dialog to
select the dataset directory
text.delete('1.0', END) # Clear the text box
text.insert(END, filename + " loaded\n") # Display the selected
directory

# Function to preprocess the dataset and extract features


def datasetPreprocessing():
global X, Y
X.clear()
Y.clear()
if os.path.exists('Model/myimg_data.txt.npy'): # Check if
preprocessed data exists
X = np.load('Model/myimg_data.txt.npy') # Load preprocessed data
Y = np.load('Model/myimg_label.txt.npy') # Load labels
else:
# Process images from the "no tumor" directory
for root, dirs, directory in os.walk(filename + "/no"):
for i in range(len(directory)):
name = directory[i]
img = cv2.imread(filename + "/no/" + name, 0) # Read the
image
ret2, th2 = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY +
cv2.THRESH_OTSU) # Apply Otsu's thresholding
img = cv2.resize(img, (128, 128)) # Resize the image
im2arr = np.array(img) # Convert to numpy array
im2arr = im2arr.reshape(128, 128, 1) # Reshape for model
input
X.append(im2arr) # Append to the dataset
Y.append(0) # Label for "no tumor"
print(filename + "/no/" + name)

# Process images from the "tumor" directory


for root, dirs, directory in os.walk(filename + "/yes"):
for i in range(len(directory)):
name = directory[i]
img = cv2.imread(filename + "/yes/" + name, 0)
ret2, th2 = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY +
cv2.THRESH_OTSU)
img = cv2.resize(img, (128, 128))
im2arr = np.array(img)
im2arr = im2arr.reshape(128, 128, 1)
X.append(im2arr)
Y.append(1) # Label for "tumor"
print(filename + "/yes/" + name)

X = np.asarray(X) # Convert to numpy array


Y = np.asarray(Y)
np.save("Model/myimg_data.txt", X) # Save the preprocessed data
np.save("Model/myimg_label.txt", Y) # Save the labels
print(X.shape)
print(Y.shape)
print(Y)
cv2.imshow('ss', X[20]) # Display a sample image
cv2.waitKey(0)
text.insert(END, "Total number of images found in dataset: " +
str(len(X)) + "\n")
text.insert(END, "Total number of classes: " + str(len(set(Y))) +
"\n\n")
text.insert(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 = np.arange(X.shape[0])
np.random.shuffle(indices) # Shuffle the dataset

x_train = X[indices]
y_train = YY[indices]

if os.path.exists('Model/model.json'): # Check if a pre-trained model


exists
with open('Model/model.json', "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
classifier.add(Convolution2D(32, 3, 3, input_shape=(128, 128, 1),
activation='relu')) # Add convolutional layer
classifier.add(MaxPooling2D(pool_size=(2, 2))) # Add max-pooling
layer
classifier.add(Convolution2D(32, 3, 3, activation='relu')) # Add
another convolutional layer
classifier.add(MaxPooling2D(pool_size=(2, 2))) # Add another
max-pooling layer
classifier.add(Flatten()) # Flatten the output
classifier.add(Dense(output_dim=128, activation='relu')) # Add a
fully connected layer
classifier.add(Dense(output_dim=2, activation='softmax')) # Add
the output layer
print(classifier.summary()) # Print the model summary
classifier.compile(optimizer='adam',
loss='categorical_crossentropy', metrics=['accuracy']) # Compile the
model
hist = classifier.fit(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/model.json", "w") as json_file:
json_file.write(model_json)
f = open('Model/history.pckl', 'wb') # Save the training history
pickle.dump(hist.history, f)
f.close()
f = open('Model/history.pckl', 'rb') # Load the training history
data = pickle.load(f)
f.close()
acc = data['accuracy']
accuracy = acc[4] * 100 # Calculate accuracy
text.insert(END, '\n\nCNN Brain Tumor Model Generated. See black
console to view layers of CNN\n\n')
text.insert(END, "CNN Brain Tumor Prediction Accuracy on Test Images:
" + str(accuracy) + "\n")

# Function to classify an input image and detect tumors


def tumorClassification():
filename = filedialog.askopenfilename(initialdir="testImages") # Open
a dialog to select an image
img = cv2.imread(filename, 0) # Read the image
img = cv2.resize(img, (128, 128)) # Resize the image
im2arr = np.array(img) # Convert to numpy array
im2arr = im2arr.reshape(1, 128, 128, 1) # Reshape for model input
XX = np.asarray(im2arr)

predicts = classifier.predict(XX) # Predict the class


print(predicts)
cls = np.argmax(predicts) # Get the predicted class
print(cls)
if cls == 0: # If no tumor is detected
img = cv2.imread(filename)
img = cv2.resize(img, (800, 500))
cv2.putText(img, 'Classification Result: ' + disease[cls], (10,
25), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 255), 2)
cv2.imshow('Classification Result: ' + disease[cls], img)
cv2.waitKey(0)
if cls == 1: # If a tumor is detected
segmented_image, edge_image = tumorSegmentation(filename) #
Segment the tumor
img = cv2.imread(filename)
img = cv2.resize(img, (800, 500))
cv2.putText(img, 'Classification Result: ' + disease[cls], (10,
25), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 255), 2)
cv2.imshow('Classification Result: ' + disease[cls], img)
cv2.imshow("Tumor Segmented Image", segmented_image)
cv2.imshow("Edge Detected Image", edge_image)
cv2.waitKey(0)

# Function to plot the training accuracy and loss graph


def graph():
f = open('Model/history.pckl', 'rb') # Load the training history
data = pickle.load(f)
f.close()

accuracy = data['accuracy']
loss = data['loss']

plt.figure(figsize=(10, 6))
plt.grid(True)
plt.xlabel('Training Epoch')
plt.ylabel('Accuracy/Loss')
plt.plot(loss, 'ro-', color='red') # Plot the loss
plt.plot(accuracy, 'ro-', color='green') # Plot the accuracy
plt.legend(['Loss', 'Accuracy'], loc='upper left')
plt.title('Brain Tumor CNN Model Training Accuracy & Loss Graph')
plt.show()

# GUI Design
font = ('times', 16, 'bold')
title = Label(main, text='Identifying Brain Tumor using X-Ray Images')
title.config(bg='darkviolet', fg='gold')
title.config(font=font)
title.config(height=3, width=120)
title.place(x=0, y=5)

font1 = ('times', 12, 'bold')


text = Text(main, height=20, width=150)
scroll = Scrollbar(text)
text.configure(yscrollcommand=scroll.set)
text.place(x=50, y=120)
text.config(font=font1)

# Buttons for various functionalities


uploadButton = Button(main, text="Upload Tumor X-Ray Images Dataset",
command=uploadDataset)
uploadButton.place(x=50, y=550)
uploadButton.config(font=font1)

preprocessButton = Button(main, text="Dataset Preprocessing & Features


Extraction", command=datasetPreprocessing)
preprocessButton.place(x=430, y=550)
preprocessButton.config(font=font1)

cnnButton = Button(main, text="Trained CNN Brain Tumor Detection Model",


command=trainTumorDetectionModel)
cnnButton.place(x=810, y=550)
cnnButton.config(font=font1)

classifyButton = Button(main, text="Brain Tumor Segmentation &


Classification", command=tumorClassification)
classifyButton.place(x=50, y=600)
classifyButton.config(font=font1)

graphButton = Button(main, text="Training Accuracy Graph", command=graph)


graphButton.place(x=430, y=600)
graphButton.config(font=font1)

main.config(bg='turquoise')
main.mainloop()

You might also like