Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
@@ -3,6 +3,7 @@ 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
|
@@ -29,41 +30,6 @@ 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 (128x128)
|
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."""
|
@@ -89,21 +55,16 @@ def resultbt():
|
|
89 |
flash('Image successfully uploaded and displayed below')
|
90 |
|
91 |
try:
|
92 |
-
#
|
93 |
-
img =
|
94 |
-
|
95 |
-
|
96 |
-
img = img.reshape(img.shape[1:]) # Reshape to (height, width, channels)
|
97 |
-
img = preprocess_imgs([img], (128, 128)) # Resize to (128, 128, 3)
|
98 |
-
|
99 |
-
# Ensure the input shape matches the model's expectation
|
100 |
-
img = img[0] # Remove unnecessary extra dimension
|
101 |
-
img = np.expand_dims(img, axis=0) # Add batch dimension to match (1, 128, 128, 3)
|
102 |
|
103 |
# Make prediction
|
104 |
-
pred = braintumor_model.predict(
|
105 |
-
prediction =
|
106 |
-
|
|
|
107 |
|
108 |
# Prepare data for MongoDB
|
109 |
result = {
|
@@ -114,8 +75,8 @@ def resultbt():
|
|
114 |
"gender": gender,
|
115 |
"age": age,
|
116 |
"image_name": filename,
|
117 |
-
"prediction":
|
118 |
-
"confidence_score":
|
119 |
"timestamp": datetime.utcnow()
|
120 |
}
|
121 |
|
@@ -123,7 +84,7 @@ def resultbt():
|
|
123 |
collection.insert_one(result)
|
124 |
|
125 |
# Return the result to the user
|
126 |
-
return render_template('resultbt.html', filename=filename, fn=firstname, ln=lastname, age=age, r=
|
127 |
finally:
|
128 |
os.remove(temp_file.name) # Ensure temporary file is deleted
|
129 |
else:
|
|
|
3 |
import cv2
|
4 |
import imutils
|
5 |
import numpy as np
|
6 |
+
from tensorflow.keras.preprocessing.image import load_img, img_to_array
|
7 |
from tensorflow.keras.models import load_model
|
8 |
from werkzeug.utils import secure_filename
|
9 |
import tempfile
|
|
|
30 |
"""Check if the file is a valid image format (png, jpg, jpeg)."""
|
31 |
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
|
32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
@app.route('/')
|
34 |
def brain_tumor():
|
35 |
"""Render the HTML form for the user to upload an image."""
|
|
|
55 |
flash('Image successfully uploaded and displayed below')
|
56 |
|
57 |
try:
|
58 |
+
# Load and preprocess the image
|
59 |
+
img = load_img(temp_file.name, target_size=(128, 128)) # Resize image to match model's input size
|
60 |
+
img_array = img_to_array(img) # Convert image to array
|
61 |
+
img_array = np.expand_dims(img_array, axis=0) / 255.0 # Normalize image and add batch dimension
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
|
63 |
# Make prediction
|
64 |
+
pred = braintumor_model.predict(img_array)
|
65 |
+
prediction = pred[0][0]
|
66 |
+
confidence = prediction if prediction > 0.5 else 1 - prediction # Calculate confidence
|
67 |
+
predicted_class = 'Tumor Detected' if prediction > 0.5 else 'No Tumor Detected' # Determine class based on threshold
|
68 |
|
69 |
# Prepare data for MongoDB
|
70 |
result = {
|
|
|
75 |
"gender": gender,
|
76 |
"age": age,
|
77 |
"image_name": filename,
|
78 |
+
"prediction": predicted_class,
|
79 |
+
"confidence_score": confidence,
|
80 |
"timestamp": datetime.utcnow()
|
81 |
}
|
82 |
|
|
|
84 |
collection.insert_one(result)
|
85 |
|
86 |
# Return the result to the user
|
87 |
+
return render_template('resultbt.html', filename=filename, fn=firstname, ln=lastname, age=age, r=predicted_class, gender=gender)
|
88 |
finally:
|
89 |
os.remove(temp_file.name) # Ensure temporary file is deleted
|
90 |
else:
|