Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -10,53 +10,57 @@ import tempfile
|
|
| 10 |
# Load the Brain Tumor CNN Model
|
| 11 |
braintumor_model = load_model('models/braintumor.h5')
|
| 12 |
|
| 13 |
-
# Configuring Flask
|
| 14 |
-
UPLOAD_FOLDER = 'static/uploads'
|
| 15 |
-
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])
|
| 16 |
-
|
| 17 |
app = Flask(__name__)
|
| 18 |
-
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
|
| 19 |
-
app.
|
| 20 |
-
|
|
|
|
|
|
|
| 21 |
|
| 22 |
def allowed_file(filename):
|
| 23 |
-
"""Check if the file is a valid image format"""
|
| 24 |
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
|
| 25 |
|
| 26 |
def preprocess_imgs(set_name, img_size):
|
| 27 |
"""
|
| 28 |
-
Preprocess
|
|
|
|
| 29 |
"""
|
| 30 |
set_new = []
|
| 31 |
for img in set_name:
|
| 32 |
-
img = cv2.resize(img, dsize=img_size, interpolation=cv2.INTER_CUBIC)
|
| 33 |
set_new.append(img)
|
| 34 |
return np.array(set_new)
|
| 35 |
|
| 36 |
def crop_imgs(set_name, add_pixels_value=0):
|
| 37 |
"""
|
| 38 |
-
Crop the region of interest (ROI) in the image
|
|
|
|
| 39 |
"""
|
| 40 |
set_new = []
|
| 41 |
for img in set_name:
|
|
|
|
| 42 |
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
| 43 |
gray = cv2.GaussianBlur(gray, (5, 5), 0)
|
| 44 |
|
| 45 |
-
# Threshold the image and find contours
|
| 46 |
thresh = cv2.threshold(gray, 45, 255, cv2.THRESH_BINARY)[1]
|
| 47 |
thresh = cv2.erode(thresh, None, iterations=2)
|
| 48 |
thresh = cv2.dilate(thresh, None, iterations=2)
|
| 49 |
|
|
|
|
| 50 |
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 51 |
cnts = imutils.grab_contours(cnts)
|
| 52 |
c = max(cnts, key=cv2.contourArea)
|
| 53 |
|
| 54 |
-
#
|
| 55 |
extLeft = tuple(c[c[:, :, 0].argmin()][0])
|
| 56 |
extRight = tuple(c[c[:, :, 0].argmax()][0])
|
| 57 |
extTop = tuple(c[c[:, :, 1].argmin()][0])
|
| 58 |
extBot = tuple(c[c[:, :, 1].argmax()][0])
|
| 59 |
|
|
|
|
| 60 |
ADD_PIXELS = add_pixels_value
|
| 61 |
new_img = img[extTop[1]-ADD_PIXELS:extBot[1]+ADD_PIXELS,
|
| 62 |
extLeft[0]-ADD_PIXELS:extRight[0]+ADD_PIXELS].copy()
|
|
@@ -66,45 +70,56 @@ def crop_imgs(set_name, add_pixels_value=0):
|
|
| 66 |
|
| 67 |
@app.route('/')
|
| 68 |
def brain_tumor():
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
return render_template('braintumor.html')
|
| 70 |
|
| 71 |
@app.route('/resultbt', methods=['POST'])
|
| 72 |
def resultbt():
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
if request.method == 'POST':
|
| 74 |
-
# Get user input from the form
|
| 75 |
firstname = request.form['firstname']
|
| 76 |
lastname = request.form['lastname']
|
| 77 |
email = request.form['email']
|
| 78 |
phone = request.form['phone']
|
| 79 |
gender = request.form['gender']
|
| 80 |
age = request.form['age']
|
| 81 |
-
file = request.files['file']
|
| 82 |
|
| 83 |
if file and allowed_file(file.filename):
|
| 84 |
-
# Use tempfile to create a temporary file path
|
| 85 |
temp_file = tempfile.NamedTemporaryFile(delete=False)
|
| 86 |
-
filename = secure_filename(file.filename)
|
| 87 |
file.save(temp_file.name) # Save file to the temp location
|
| 88 |
|
| 89 |
flash('Image successfully uploaded and displayed below')
|
| 90 |
|
| 91 |
-
# Read
|
| 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 |
-
# Model prediction
|
| 98 |
pred = braintumor_model.predict(img)
|
| 99 |
if pred < 0.5:
|
| 100 |
-
pred = 0
|
| 101 |
else:
|
| 102 |
-
pred = 1
|
| 103 |
|
|
|
|
| 104 |
return render_template('resultbt.html', filename=filename, fn=firstname, ln=lastname, age=age, r=pred, gender=gender)
|
| 105 |
else:
|
|
|
|
| 106 |
flash('Allowed image types are - png, jpg, jpeg')
|
| 107 |
return redirect(request.url)
|
| 108 |
|
| 109 |
if __name__ == '__main__':
|
|
|
|
| 110 |
app.run(debug=True)
|
|
|
|
| 10 |
# Load the Brain Tumor CNN Model
|
| 11 |
braintumor_model = load_model('models/braintumor.h5')
|
| 12 |
|
| 13 |
+
# Configuring Flask application
|
|
|
|
|
|
|
|
|
|
| 14 |
app = Flask(__name__)
|
| 15 |
+
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 # Disable caching for images
|
| 16 |
+
app.secret_key = "nielitchandigarhpunjabpolice" # Secret key for session management
|
| 17 |
+
|
| 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
|
| 24 |
|
| 25 |
def preprocess_imgs(set_name, img_size):
|
| 26 |
"""
|
| 27 |
+
Preprocess images by resizing them to the target size (224x224 for VGG16)
|
| 28 |
+
and applying appropriate resizing techniques.
|
| 29 |
"""
|
| 30 |
set_new = []
|
| 31 |
for img in set_name:
|
| 32 |
+
img = cv2.resize(img, dsize=img_size, interpolation=cv2.INTER_CUBIC) # Resize image
|
| 33 |
set_new.append(img)
|
| 34 |
return np.array(set_new)
|
| 35 |
|
| 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()
|
|
|
|
| 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)
|