Anuj25077/cnn
1
1### **Code Explanation for Brain Tumor Detection Application Using Flask**
2
3This Flask-based application allows users to upload an image (like an MRI scan) to predict if a brain tumor is detected using a pre-trained CNN (Convolutional Neural Network) model. The results, along with user details, are saved in a MongoDB database for review.
4
5---
6
7### **1. Importing Required Libraries**
8
9```python
10from flask import Flask, flash, request, redirect, render_template
11import os
12import cv2
13import imutils
14import numpy as np
15from tensorflow.keras.models import load_model
16from werkzeug.utils import secure_filename
17import tempfile
18from pymongo import MongoClient
19from datetime import datetime
20```
21
22- **Flask**: A lightweight web framework to create web applications.
23- **OpenCV (cv2)**: Library for image processing.
24- **imutils**: Helper functions for image manipulation.
25- **NumPy**: Array and mathematical operations.
26- **TensorFlow/Keras**: To load the pre-trained brain tumor detection model.
27- **MongoDB**: To store user inputs and model predictions.
28- **Werkzeug**: For securely handling file uploads.
29- **Datetime**: To save the timestamp for each prediction.
30
31---
32
33### **2. Loading the Pre-trained Model**
34
35```python
36braintumor_model = load_model('models/braintumor.h5')
37```
38- The brain tumor model (`braintumor.h5`) is loaded. This is a CNN-based model trained to detect brain tumors from images.
39
40---
41
42### **3. Flask Application Configuration**
43
44```python
45app = Flask(__name__)
46app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 # Disable caching
47app.secret_key = "nielitchandigarhpunjabpolice"
48```
49
50- Flask is initialized, and caching for images is disabled to ensure updated images load after upload.
51- A **secret key** is set for session management, which helps in managing messages (like flash messages).
52
53---
54
55### **4. MongoDB Connection**
56
57```python
58client = MongoClient("mongodb+srv://test:test@cluster0.sxci1.mongodb.net/?retryWrites=true&w=majority")
59db = client['brain_tumor_detection'] # Database name
60collection = db['predictions'] # Collection name
61```
62- Connects to **MongoDB Atlas** (cloud-hosted database).
63- A database named `brain_tumor_detection` and collection `predictions` are created to store user details and predictions.
64
65---
66
67### **5. File Upload Helper Function**
68
69```python
70ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])
71
72def allowed_file(filename):
73 return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
74```
75- Only files with extensions **png, jpg, jpeg** are allowed to ensure proper image input.
76
77---
78
79### **6. Image Preprocessing**
80
81**a. `preprocess_imgs`: Resizing Images**
82
83```python
84def preprocess_imgs(set_name, img_size):
85 set_new = []
86 for img in set_name:
87 img = cv2.resize(img, dsize=img_size, interpolation=cv2.INTER_CUBIC)
88 set_new.append(img)
89 return np.array(set_new)
90```
91- Resizes the input image to a specific size (224x224) required by the model.
92
93**b. `crop_imgs`: Region of Interest (ROI) Extraction**
94
95```python
96def crop_imgs(set_name, add_pixels_value=0):
97 set_new = []
98 for img in set_name:
99 gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
100 gray = cv2.GaussianBlur(gray, (5, 5), 0)
101 thresh = cv2.threshold(gray, 45, 255, cv2.THRESH_BINARY)[1]
102 cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
103 c = max(cnts, key=cv2.contourArea)
104 extLeft = tuple(c[c[:, :, 0].argmin()][0])
105 extRight = tuple(c[c[:, :, 0].argmax()][0])
106 extTop = tuple(c[c[:, :, 1].argmin()][0])
107 extBot = tuple(c[c[:, :, 1].argmax()][0])
108 new_img = img[extTop[1]:extBot[1], extLeft[0]:extRight[0]].copy()
109 set_new.append(new_img)
110 return np.array(set_new)
111```
112- This function identifies the **region of interest (ROI)**, cropping only the area where the brain is located for better accuracy.
113
114---
115
116### **7. Routes in Flask**
117
118**a. `/` Route - Main Page**
119
120```python
121@app.route('/')
122def brain_tumor():
123 return render_template('braintumor.html')
124```
125- Displays the main upload form (`braintumor.html`).
126
127**b. `/resultbt` Route - Prediction**
128
129```python
130@app.route('/resultbt', methods=['POST'])
131def resultbt():
132 # 1. Extract user inputs
133 firstname = request.form['firstname']
134 file = request.files['file']
135
136 # 2. Validate image
137 if file and allowed_file(file.filename):
138 temp_file = tempfile.NamedTemporaryFile(delete=False)
139 file.save(temp_file.name)
140
141 # 3. Process Image
142 img = cv2.imread(temp_file.name)
143 img = crop_imgs([img])
144 img = preprocess_imgs([img], (224, 224))
145
146 # 4. Predict
147 pred = braintumor_model.predict(img)
148 prediction = 'Tumor Detected' if pred[0][0] >= 0.5 else 'No Tumor Detected'
149 confidence_score = float(pred[0][0])
150
151 # 5. Save to MongoDB
152 result = {
153 "firstname": firstname,
154 "prediction": prediction,
155 "confidence_score": confidence_score,
156 "timestamp": datetime.utcnow()
157 }
158 collection.insert_one(result)
159
160 # 6. Return Results
161 return render_template('resultbt.html', r=prediction)
162 else:
163 flash('Invalid file format!')
164 return redirect(request.url)
165```
166- **Step-by-step Flow**:
167 1. Accept user inputs and uploaded image.
168 2. Validate the file format.
169 3. Preprocess the image (crop and resize).
170 4. Use the CNN model to predict if there is a tumor.๐
171 5. Save the prediction and user details to MongoDB.
172 6. Return the result.
173
174**c. `/dbresults` Route - Fetch Predictions**
175
176```python
177@app.route('/dbresults')
178def dbresults():
179 all_results = collection.find().sort("timestamp", -1)
180 tumor_count = sum(1 for r in all_results if r['prediction'] == 'Tumor Detected')
181 total_patients = collection.count_documents({})
182 return render_template('dbresults.html', total_patients=total_patients, tumor_count=tumor_count)
183```
184- Fetches all predictions from MongoDB and aggregates results (total patients, tumors detected).
185
186---
187
188### **8. Running the App**
189
190```python
191if __name__ == '__main__':
192 app.run(debug=True)
193```
194- Runs the Flask application in **debug mode**.
195
196---
197
198### **Summary of Flow**
1991. User uploads an MRI image and provides basic details.
2002. Image is preprocessed (cropped, resized) for the CNN model.
2013. The model predicts if a **brain tumor is detected** or not.
2024. Results are stored in MongoDB and displayed back to the user.
2035. Admins can view all results via the `/dbresults` route.
204
205---
206
207### **Tips**
2081. **Flask Routes** handle user requests (`/`, `/resultbt`, `/dbresults`).
2092. **OpenCV** helps preprocess images.
2103. **MongoDB** stores user details and model predictions.
2114. **Model Prediction** is done via a pre-trained Keras model.
2125. Templates (`braintumor.html`, `resultbt.html`) are used to display data.
213
214 