LovnishVerma commited on
Commit
5772bc5
·
verified ·
1 Parent(s): e127e7e

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +55 -38
main.py CHANGED
@@ -6,6 +6,8 @@ import numpy as np
6
  from tensorflow.keras.models import load_model
7
  from werkzeug.utils import secure_filename
8
  import tempfile
 
 
9
 
10
  # Load the Brain Tumor CNN Model
11
  braintumor_model = load_model('models/braintumor.h5')
@@ -18,6 +20,11 @@ app.secret_key = "nielitchandigarhpunjabpolice" # Secret key for session manage
18
  # Allowed image file extensions
19
  ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])
20
 
 
 
 
 
 
21
  def allowed_file(filename):
22
  """Check if the file is a valid image format (png, jpg, jpeg)."""
23
  return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
@@ -36,90 +43,100 @@ def preprocess_imgs(set_name, img_size):
36
  def crop_imgs(set_name, add_pixels_value=0):
37
  """
38
  Crop the region of interest (ROI) in the image for brain tumor detection.
39
- This method finds contours in the image, then crops the detected tumor region.
40
  """
41
  set_new = []
42
  for img in set_name:
43
- # Convert to grayscale and apply Gaussian blur
44
  gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
45
  gray = cv2.GaussianBlur(gray, (5, 5), 0)
46
-
47
- # Threshold the image and find contours
48
  thresh = cv2.threshold(gray, 45, 255, cv2.THRESH_BINARY)[1]
49
  thresh = cv2.erode(thresh, None, iterations=2)
50
  thresh = cv2.dilate(thresh, None, iterations=2)
51
-
52
- # Find the largest contour and crop the image around it
53
  cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
54
  cnts = imutils.grab_contours(cnts)
55
  c = max(cnts, key=cv2.contourArea)
56
-
57
- # Get the extreme points (left, right, top, bottom) of the contour for cropping
58
  extLeft = tuple(c[c[:, :, 0].argmin()][0])
59
  extRight = tuple(c[c[:, :, 0].argmax()][0])
60
  extTop = tuple(c[c[:, :, 1].argmin()][0])
61
  extBot = tuple(c[c[:, :, 1].argmax()][0])
62
-
63
- # Add some extra pixels around the contour to ensure the full tumor is captured
64
  ADD_PIXELS = add_pixels_value
65
  new_img = img[extTop[1]-ADD_PIXELS:extBot[1]+ADD_PIXELS,
66
  extLeft[0]-ADD_PIXELS:extRight[0]+ADD_PIXELS].copy()
67
  set_new.append(new_img)
68
-
69
  return np.array(set_new)
70
 
71
  @app.route('/')
72
  def brain_tumor():
73
- """
74
- The main page that renders the HTML form for the user to upload an image
75
- and input their details.
76
- """
77
  return render_template('braintumor.html')
78
 
79
  @app.route('/resultbt', methods=['POST'])
80
  def resultbt():
81
- """
82
- The result page that processes the uploaded image, makes predictions using
83
- the trained brain tumor detection model, and displays the result.
84
- """
85
  if request.method == 'POST':
86
- # Get user input from the form (name, email, phone, etc.)
87
  firstname = request.form['firstname']
88
  lastname = request.form['lastname']
89
  email = request.form['email']
90
  phone = request.form['phone']
91
  gender = request.form['gender']
92
  age = request.form['age']
93
- file = request.files['file'] # The uploaded image file
94
 
95
  if file and allowed_file(file.filename):
96
- # Use tempfile to create a temporary file path for the uploaded image
97
  temp_file = tempfile.NamedTemporaryFile(delete=False)
98
- filename = secure_filename(file.filename) # Secure the filename
99
- file.save(temp_file.name) # Save file to the temp location
100
 
101
  flash('Image successfully uploaded and displayed below')
102
 
103
- # Read the image, crop the region of interest (tumor), and preprocess
104
  img = cv2.imread(temp_file.name)
105
- img = crop_imgs([img]) # Crop the tumor area from the image
106
- img = img.reshape(img.shape[1:]) # Reshape for the model input
107
- img = preprocess_imgs([img], (224, 224)) # Resize image to 224x224
108
 
109
- # Model prediction: 0 - no tumor, 1 - tumor detected
110
  pred = braintumor_model.predict(img)
111
- if pred < 0.5:
112
- pred = 0 # No tumor detected
113
- else:
114
- pred = 1 # Tumor detected
115
-
116
- # Return the result to the user, including input data and prediction
117
- return render_template('resultbt.html', filename=filename, fn=firstname, ln=lastname, age=age, r=pred, gender=gender)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  else:
119
- # If the file is not valid, show an error message
120
  flash('Allowed image types are - png, jpg, jpeg')
121
  return redirect(request.url)
122
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  if __name__ == '__main__':
124
- # Run the app in debug mode for development purposes
125
  app.run(debug=True)
 
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')
 
20
  # Allowed image file extensions
21
  ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])
22
 
23
+ # Connect to MongoDB Atlas
24
+ client = MongoClient("mongodb+srv://test:test@cluster0.sxci1.mongodb.net/?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
 
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 and render them in a template."""
128
+ # Fetch all documents from the MongoDB collection
129
+ all_results = collection.find() # Returns a cursor
130
+
131
+ # Convert cursor to a list of dictionaries
132
+ results_list = []
133
+ for result in all_results:
134
+ result['_id'] = str(result['_id']) # Convert ObjectId to string for JSON serialization
135
+ results_list.append(result)
136
+
137
+ # Pass the results to the HTML template
138
+ return render_template('dbresults.html', results=results_list)
139
+
140
+
141
  if __name__ == '__main__':
 
142
  app.run(debug=True)