Spaces:
Running
Running
Update main.py
Browse files
main.py
CHANGED
@@ -1,157 +1,163 @@
|
|
1 |
-
from flask import Flask, flash, request, redirect, render_template
|
2 |
-
import os
|
3 |
-
import cv2
|
4 |
-
import imutils
|
5 |
-
import numpy as np
|
6 |
-
from tensorflow.keras.models import load_model
|
7 |
-
from werkzeug.utils import secure_filename
|
8 |
-
import tempfile
|
9 |
-
from pymongo import MongoClient
|
10 |
-
from datetime import datetime
|
11 |
-
|
12 |
-
# Load the Brain Tumor CNN Model
|
13 |
-
braintumor_model = load_model('models/braintumor.h5')
|
14 |
-
|
15 |
-
# Configuring Flask application
|
16 |
-
app = Flask(__name__)
|
17 |
-
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 # Disable caching for images
|
18 |
-
app.secret_key = "nielitchandigarhpunjabpolice" # Secret key for session management
|
19 |
-
|
20 |
-
# Allowed image file extensions
|
21 |
-
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])
|
22 |
-
|
23 |
-
# Connect to MongoDB Atlas
|
24 |
-
client = MongoClient("mongodb+srv://test:[email protected]/?retryWrites=true&w=majority")
|
25 |
-
db = client['brain_tumor_detection'] # Database name
|
26 |
-
collection = db['predictions'] # Collection name
|
27 |
-
|
28 |
-
def allowed_file(filename):
|
29 |
-
"""Check if the file is a valid image format (png, jpg, jpeg)."""
|
30 |
-
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
|
31 |
-
|
32 |
-
def preprocess_imgs(set_name, img_size):
|
33 |
-
"""
|
34 |
-
Preprocess images by resizing them to the target size (224x224 for VGG16)
|
35 |
-
and applying appropriate resizing techniques.
|
36 |
-
"""
|
37 |
-
set_new = []
|
38 |
-
for img in set_name:
|
39 |
-
img = cv2.resize(img, dsize=img_size, interpolation=cv2.INTER_CUBIC) # Resize image
|
40 |
-
set_new.append(img)
|
41 |
-
return np.array(set_new)
|
42 |
-
|
43 |
-
def crop_imgs(set_name, add_pixels_value=0):
|
44 |
-
"""
|
45 |
-
Crop the region of interest (ROI) in the image for brain tumor detection.
|
46 |
-
"""
|
47 |
-
set_new = []
|
48 |
-
for img in set_name:
|
49 |
-
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
50 |
-
gray = cv2.GaussianBlur(gray, (5, 5), 0)
|
51 |
-
thresh = cv2.threshold(gray, 45, 255, cv2.THRESH_BINARY)[1]
|
52 |
-
thresh = cv2.erode(thresh, None, iterations=2)
|
53 |
-
thresh = cv2.dilate(thresh, None, iterations=2)
|
54 |
-
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
55 |
-
cnts = imutils.grab_contours(cnts)
|
56 |
-
c = max(cnts, key=cv2.contourArea)
|
57 |
-
extLeft = tuple(c[c[:, :, 0].argmin()][0])
|
58 |
-
extRight = tuple(c[c[:, :, 0].argmax()][0])
|
59 |
-
extTop = tuple(c[c[:, :, 1].argmin()][0])
|
60 |
-
extBot = tuple(c[c[:, :, 1].argmax()][0])
|
61 |
-
ADD_PIXELS = add_pixels_value
|
62 |
-
new_img = img[extTop[1]-ADD_PIXELS:extBot[1]+ADD_PIXELS,
|
63 |
-
extLeft[0]-ADD_PIXELS:extRight[0]+ADD_PIXELS].copy()
|
64 |
-
set_new.append(new_img)
|
65 |
-
return np.array(set_new)
|
66 |
-
|
67 |
-
@app.route('/')
|
68 |
-
def brain_tumor():
|
69 |
-
"""Render the HTML form for the user to upload an image."""
|
70 |
-
return render_template('braintumor.html')
|
71 |
-
|
72 |
-
@app.route('/resultbt', methods=['POST'])
|
73 |
-
def resultbt():
|
74 |
-
"""Process the uploaded image and save prediction results to MongoDB."""
|
75 |
-
if request.method == 'POST':
|
76 |
-
firstname = request.form['firstname']
|
77 |
-
lastname = request.form['lastname']
|
78 |
-
email = request.form['email']
|
79 |
-
phone = request.form['phone']
|
80 |
-
gender = request.form['gender']
|
81 |
-
age = request.form['age']
|
82 |
-
file = request.files['file']
|
83 |
-
|
84 |
-
if file and allowed_file(file.filename):
|
85 |
-
temp_file = tempfile.NamedTemporaryFile(delete=False)
|
86 |
-
filename = secure_filename(file.filename)
|
87 |
-
file.save(temp_file.name)
|
88 |
-
|
89 |
-
flash('Image successfully uploaded and displayed below')
|
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 |
app.run(debug=True)
|
|
|
1 |
+
from flask import Flask, flash, request, redirect, render_template
|
2 |
+
import os
|
3 |
+
import cv2
|
4 |
+
import imutils
|
5 |
+
import numpy as np
|
6 |
+
from tensorflow.keras.models import load_model
|
7 |
+
from werkzeug.utils import secure_filename
|
8 |
+
import tempfile
|
9 |
+
from pymongo import MongoClient
|
10 |
+
from datetime import datetime
|
11 |
+
|
12 |
+
# Load the Brain Tumor CNN Model
|
13 |
+
braintumor_model = load_model('models/braintumor.h5')
|
14 |
+
|
15 |
+
# Configuring Flask application
|
16 |
+
app = Flask(__name__)
|
17 |
+
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 # Disable caching for images
|
18 |
+
app.secret_key = "nielitchandigarhpunjabpolice" # Secret key for session management
|
19 |
+
|
20 |
+
# Allowed image file extensions
|
21 |
+
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])
|
22 |
+
|
23 |
+
# Connect to MongoDB Atlas
|
24 |
+
client = MongoClient("mongodb+srv://test:[email protected]/?retryWrites=true&w=majority")
|
25 |
+
db = client['brain_tumor_detection'] # Database name
|
26 |
+
collection = db['predictions'] # Collection name
|
27 |
+
|
28 |
+
def allowed_file(filename):
|
29 |
+
"""Check if the file is a valid image format (png, jpg, jpeg)."""
|
30 |
+
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
|
31 |
+
|
32 |
+
def preprocess_imgs(set_name, img_size):
|
33 |
+
"""
|
34 |
+
Preprocess images by resizing them to the target size (224x224 for VGG16)
|
35 |
+
and applying appropriate resizing techniques.
|
36 |
+
"""
|
37 |
+
set_new = []
|
38 |
+
for img in set_name:
|
39 |
+
img = cv2.resize(img, dsize=img_size, interpolation=cv2.INTER_CUBIC) # Resize image
|
40 |
+
set_new.append(img)
|
41 |
+
return np.array(set_new)
|
42 |
+
|
43 |
+
def crop_imgs(set_name, add_pixels_value=0):
|
44 |
+
"""
|
45 |
+
Crop the region of interest (ROI) in the image for brain tumor detection.
|
46 |
+
"""
|
47 |
+
set_new = []
|
48 |
+
for img in set_name:
|
49 |
+
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
50 |
+
gray = cv2.GaussianBlur(gray, (5, 5), 0)
|
51 |
+
thresh = cv2.threshold(gray, 45, 255, cv2.THRESH_BINARY)[1]
|
52 |
+
thresh = cv2.erode(thresh, None, iterations=2)
|
53 |
+
thresh = cv2.dilate(thresh, None, iterations=2)
|
54 |
+
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
55 |
+
cnts = imutils.grab_contours(cnts)
|
56 |
+
c = max(cnts, key=cv2.contourArea)
|
57 |
+
extLeft = tuple(c[c[:, :, 0].argmin()][0])
|
58 |
+
extRight = tuple(c[c[:, :, 0].argmax()][0])
|
59 |
+
extTop = tuple(c[c[:, :, 1].argmin()][0])
|
60 |
+
extBot = tuple(c[c[:, :, 1].argmax()][0])
|
61 |
+
ADD_PIXELS = add_pixels_value
|
62 |
+
new_img = img[extTop[1]-ADD_PIXELS:extBot[1]+ADD_PIXELS,
|
63 |
+
extLeft[0]-ADD_PIXELS:extRight[0]+ADD_PIXELS].copy()
|
64 |
+
set_new.append(new_img)
|
65 |
+
return np.array(set_new)
|
66 |
+
|
67 |
+
@app.route('/')
|
68 |
+
def brain_tumor():
|
69 |
+
"""Render the HTML form for the user to upload an image."""
|
70 |
+
return render_template('braintumor.html')
|
71 |
+
|
72 |
+
@app.route('/resultbt', methods=['POST'])
|
73 |
+
def resultbt():
|
74 |
+
"""Process the uploaded image and save prediction results to MongoDB."""
|
75 |
+
if request.method == 'POST':
|
76 |
+
firstname = request.form['firstname']
|
77 |
+
lastname = request.form['lastname']
|
78 |
+
email = request.form['email']
|
79 |
+
phone = request.form['phone']
|
80 |
+
gender = request.form['gender']
|
81 |
+
age = request.form['age']
|
82 |
+
file = request.files['file']
|
83 |
+
|
84 |
+
if file and allowed_file(file.filename):
|
85 |
+
temp_file = tempfile.NamedTemporaryFile(delete=False)
|
86 |
+
filename = secure_filename(file.filename)
|
87 |
+
file.save(temp_file.name)
|
88 |
+
|
89 |
+
flash('Image successfully uploaded and displayed below')
|
90 |
+
|
91 |
+
try:
|
92 |
+
# Process the image
|
93 |
+
img = cv2.imread(temp_file.name)
|
94 |
+
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Convert to RGB
|
95 |
+
img = crop_imgs([img])
|
96 |
+
img = img.reshape(img.shape[1:])
|
97 |
+
img = preprocess_imgs([img], (128, 128)) # Match model's input size
|
98 |
+
img = np.expand_dims(img, axis=0) # Add batch dimension
|
99 |
+
|
100 |
+
# Make prediction
|
101 |
+
pred = braintumor_model.predict(img)
|
102 |
+
prediction = 'Tumor Detected' if pred[0][0] >= 0.5 else 'No Tumor Detected'
|
103 |
+
confidence_score = float(pred[0][0])
|
104 |
+
|
105 |
+
# Prepare data for MongoDB
|
106 |
+
result = {
|
107 |
+
"firstname": firstname,
|
108 |
+
"lastname": lastname,
|
109 |
+
"email": email,
|
110 |
+
"phone": phone,
|
111 |
+
"gender": gender,
|
112 |
+
"age": age,
|
113 |
+
"image_name": filename,
|
114 |
+
"prediction": prediction,
|
115 |
+
"confidence_score": confidence_score,
|
116 |
+
"timestamp": datetime.utcnow()
|
117 |
+
}
|
118 |
+
|
119 |
+
# Insert data into MongoDB
|
120 |
+
collection.insert_one(result)
|
121 |
+
|
122 |
+
# Return the result to the user
|
123 |
+
return render_template('resultbt.html', filename=filename, fn=firstname, ln=lastname, age=age, r=prediction, gender=gender)
|
124 |
+
finally:
|
125 |
+
os.remove(temp_file.name) # Ensure temporary file is deleted
|
126 |
+
else:
|
127 |
+
flash('Allowed image types are - png, jpg, jpeg')
|
128 |
+
return redirect(request.url)
|
129 |
+
|
130 |
+
|
131 |
+
@app.route('/dbresults')
|
132 |
+
def dbresults():
|
133 |
+
"""Fetch all results from MongoDB, show aggregated data, and render in a template."""
|
134 |
+
# Fetch all documents from MongoDB, sorted by timestamp in descending order
|
135 |
+
all_results = collection.find().sort("timestamp", -1) # Sort by timestamp, latest first
|
136 |
+
|
137 |
+
# Convert cursor to a list of dictionaries
|
138 |
+
results_list = []
|
139 |
+
tumor_count = 0
|
140 |
+
no_tumor_count = 0
|
141 |
+
|
142 |
+
for result in all_results:
|
143 |
+
result['_id'] = str(result['_id']) # Convert ObjectId to string for JSON serialization
|
144 |
+
results_list.append(result)
|
145 |
+
|
146 |
+
# Count total patients with tumor and without tumor
|
147 |
+
if result['prediction'] == 'Tumor Detected':
|
148 |
+
tumor_count += 1
|
149 |
+
else:
|
150 |
+
no_tumor_count += 1
|
151 |
+
|
152 |
+
total_patients = len(results_list) # Total number of patients
|
153 |
+
|
154 |
+
# Pass the results and aggregated counts to the HTML template
|
155 |
+
return render_template('dbresults.html',
|
156 |
+
results=results_list,
|
157 |
+
total_patients=total_patients,
|
158 |
+
tumor_count=tumor_count,
|
159 |
+
no_tumor_count=no_tumor_count)
|
160 |
+
|
161 |
+
|
162 |
+
if __name__ == '__main__':
|
163 |
app.run(debug=True)
|