LovnishVerma commited on
Commit
d3584f9
·
verified ·
1 Parent(s): 7b46bd8

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +162 -156
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
- # Process the image
92
- img = cv2.imread(temp_file.name)
93
- img = crop_imgs([img])
94
- img = img.reshape(img.shape[1:])
95
- img = preprocess_imgs([img], (224, 224))
96
-
97
- # Make prediction
98
- pred = braintumor_model.predict(img)
99
- prediction = 'Tumor Detected' if pred[0][0] >= 0.5 else 'No Tumor Detected'
100
- confidence_score = float(pred[0][0])
101
-
102
- # Prepare data for MongoDB
103
- result = {
104
- "firstname": firstname,
105
- "lastname": lastname,
106
- "email": email,
107
- "phone": phone,
108
- "gender": gender,
109
- "age": age,
110
- "image_name": filename,
111
- "prediction": prediction,
112
- "confidence_score": confidence_score,
113
- "timestamp": datetime.utcnow()
114
- }
115
-
116
- # Insert data into MongoDB
117
- collection.insert_one(result)
118
-
119
- # Return the result to the user
120
- return render_template('resultbt.html', filename=filename, fn=firstname, ln=lastname, age=age, r=prediction, gender=gender)
121
- else:
122
- flash('Allowed image types are - png, jpg, jpeg')
123
- return redirect(request.url)
124
-
125
- @app.route('/dbresults')
126
- def dbresults():
127
- """Fetch all results from MongoDB, show aggregated data, and render in a template."""
128
- # Fetch all documents from MongoDB, sorted by timestamp in descending order
129
- all_results = collection.find().sort("timestamp", -1) # Sort by timestamp, latest first
130
-
131
- # Convert cursor to a list of dictionaries
132
- results_list = []
133
- tumor_count = 0
134
- no_tumor_count = 0
135
-
136
- for result in all_results:
137
- result['_id'] = str(result['_id']) # Convert ObjectId to string for JSON serialization
138
- results_list.append(result)
139
-
140
- # Count total patients with tumor and without tumor
141
- if result['prediction'] == 'Tumor Detected':
142
- tumor_count += 1
143
- else:
144
- no_tumor_count += 1
145
-
146
- total_patients = len(results_list) # Total number of patients
147
-
148
- # Pass the results and aggregated counts to the HTML template
149
- return render_template('dbresults.html',
150
- results=results_list,
151
- total_patients=total_patients,
152
- tumor_count=tumor_count,
153
- no_tumor_count=no_tumor_count)
154
-
155
-
156
- if __name__ == '__main__':
 
 
 
 
 
 
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)