Surendradjh commited on
Commit
312dfa3
Β·
verified Β·
1 Parent(s): 2f22d9a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +15 -169
app.py CHANGED
@@ -1,151 +1,3 @@
1
- # import streamlit as st
2
- # import numpy as np
3
- # import cv2
4
- # from keras.models import load_model
5
- # from keras.preprocessing.image import img_to_array
6
- # from PIL import Image
7
-
8
- # # Page config
9
- # st.set_page_config(
10
- # page_title="😷 Smart Face Mask Detection",
11
- # layout="wide",
12
- # page_icon="😷"
13
- # )
14
-
15
- # # Load model with caching
16
- # @st.cache_resource
17
- # def load_model_cached():
18
- # return load_model("project_face_mask_detection.keras")
19
-
20
- # model = load_model_cached()
21
-
22
- # # Haar Cascade for face detection
23
- # face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
24
-
25
- # # Sidebar content
26
- # with st.sidebar:
27
- # st.title("🧠 About This App")
28
- # st.markdown("""
29
- # This app uses deep learning to detect whether a person is wearing a face mask.
30
-
31
- # - Upload or capture an image.
32
- # - Get instant feedback.
33
- # - Built with Streamlit & Keras.
34
- # """)
35
- # st.info("Tip: Use well-lit images with clear faces for best results.")
36
- # st.markdown("---")
37
- # st.caption("πŸ“ Developed by Surendra β€’ 2025")
38
-
39
- # # Resize function
40
- # def resize_image(image, max_size=(400, 400)):
41
- # image = image.copy()
42
- # image.thumbnail(max_size) # Maintains aspect ratio
43
- # return image
44
-
45
- # # Detection function
46
- # def detect_and_predict(image_input):
47
- # image_np = np.array(image_input.convert("RGB"))
48
- # gray = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY)
49
- # faces = face_cascade.detectMultiScale(gray, 1.1, 4)
50
-
51
- # if len(faces) == 0:
52
- # return image_input, None, "⚠️ No face detected"
53
-
54
- # x, y, w, h = faces[0]
55
- # face_roi = image_np[y:y+h, x:x+w]
56
- # face_pil = Image.fromarray(face_roi).resize((200, 200))
57
- # img_array = img_to_array(face_pil) / 255.0
58
- # img_array = np.expand_dims(img_array, axis=0)
59
-
60
- # prediction = model.predict(img_array)[0][0]
61
- # confidence = (1 - prediction) if prediction < 0.5 else prediction
62
- # label = "βœ… Mask Detected" if prediction < 0.5 else "🚫 No Mask Detected"
63
-
64
- # # Draw results
65
- # color = (0, 255, 0) if prediction < 0.5 else (255, 0, 0)
66
- # cv2.rectangle(image_np, (x, y), (x + w, y + h), color, 2)
67
- # cv2.putText(image_np, f"{label} ({confidence*100:.2f}%)", (x, y - 10),
68
- # cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
69
-
70
- # return Image.fromarray(image_np), confidence, label
71
-
72
- # # App title
73
- # st.markdown("<h1 style='text-align: center;'>😷 AI Face Mask Detection System</h1>", unsafe_allow_html=True)
74
- # st.markdown("<p style='text-align: center;'>Upload or capture an image to analyze mask presence.</p>", unsafe_allow_html=True)
75
-
76
- # # Input choice
77
- # input_choice = st.selectbox("Choose Input Method", ["πŸ“€ Upload Image", "πŸ“· Use Webcam"])
78
-
79
- # if input_choice == "πŸ“€ Upload Image":
80
- # uploaded_file = st.file_uploader("Choose an image file", type=["jpg", "jpeg", "png"])
81
-
82
-
83
- # if uploaded_file:
84
- # col1, col2 = st.columns(2)
85
- # image_input = resize_image(Image.open(uploaded_file))
86
- # image_np = np.array(image_input)
87
- # resized_img = cv2.resize(image_np, (400, 400))
88
- # resized_img_rgb = cv2.cvtColor(resized_img, cv2.COLOR_BGR2RGB)
89
- # # resized_img =cv2.resize(image_input,(400,400)) #image_input.resize((400, 400)) # width=400, height=150
90
- # with col1:
91
- # # st.image(image_input, caption="Uploaded Image", width=400,height = 150)#use_container_width=True)
92
- # # st.image(resized_img, caption="Uploaded Image")
93
- # st.image(resized_img_rgb, caption="Uploaded Image")
94
-
95
- # with st.spinner("Analyzing with AI model..."):
96
- # result_img, confidence, label = detect_and_predict(image_input)
97
-
98
- # # col1, col2 = st.columns(2)
99
- # with col2:
100
- # # resized_img = result_img.resize((400, 400))
101
- # result_img_pil = Image.fromarray(result_img)
102
- # resized_img = result_img_pil.resize((400, 400))
103
-
104
- # st.image(resized_img, caption="Detection Output")#, width=400,height = 150)#use_container_width=True)
105
- # # with col2:
106
- # if confidence is not None:
107
- # st.metric("Confidence Score", f"{confidence*100:.2f}%")
108
- # if "Mask" in label:
109
- # st.success(label)
110
- # else:
111
- # st.error(label)
112
- # else:
113
- # st.warning(label)
114
-
115
-
116
-
117
- # elif input_choice == "πŸ“· Use Webcam":
118
- # col1, col2 = st.columns([1, 3])
119
- # with col1:
120
- # camera_image = st.camera_input("Take a picture using webcam")
121
- # if camera_image:
122
- # image_input = resize_image(Image.open(camera_image))
123
- # # st.image(image_input, caption="Webcam Snapshot", use_container_width=True)
124
-
125
- # with st.spinner("Analyzing..."):
126
- # result_img, confidence, label = detect_and_predict(image_input)
127
-
128
- # # col1, col2 = st.columns(2)
129
- # with col2:
130
- # st.write("Resulted Image")
131
- # # resized_img = result_img.resize((400, 400)) # width=400, height=150
132
- # # resized_img = result_img.resize((200, 200))
133
- # result_img_pil = Image.fromarray(result_img)
134
- # resized_img = result_img_pil.resize((400, 400))
135
-
136
- # st.image(resized_img, caption="Detection Output")#, width=400,height = 150)
137
- # # st.image(result_img, caption="Detection Output", use_container_width=True).resize(200,200)
138
- # # with col2:
139
- # if confidence is not None:
140
- # st.metric("Confidence Score", f"{confidence*100:.2f}%")
141
- # if "Mask" in label:
142
- # st.success(label)
143
- # else:
144
- # st.error(label)
145
- # else:
146
- # st.warning(label)
147
-
148
-
149
  import streamlit as st
150
  import numpy as np
151
  import cv2
@@ -170,7 +22,7 @@ model = load_model_cached()
170
  # Haar Cascade for face detection
171
  face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
172
 
173
- # Sidebar content
174
  with st.sidebar:
175
  st.title("🧠 About This App")
176
  st.markdown("""
@@ -184,10 +36,10 @@ with st.sidebar:
184
  st.markdown("---")
185
  st.caption("πŸ“ Developed by Surendra β€’ 2025")
186
 
187
- # Resize function
188
  def resize_image(image, max_size=(400, 400)):
189
  image = image.copy()
190
- image.thumbnail(max_size) # Maintains aspect ratio
191
  return image
192
 
193
  # Detection function
@@ -209,7 +61,7 @@ def detect_and_predict(image_input):
209
  confidence = (1 - prediction) if prediction < 0.5 else prediction
210
  label = "βœ… Mask Detected" if prediction < 0.5 else "🚫 No Mask Detected"
211
 
212
- # Draw results
213
  color = (0, 255, 0) if prediction < 0.5 else (255, 0, 0)
214
  cv2.rectangle(image_np, (x, y), (x + w, y + h), color, 2)
215
  cv2.putText(image_np, f"{label} ({confidence*100:.2f}%)", (x, y - 10),
@@ -217,41 +69,38 @@ def detect_and_predict(image_input):
217
 
218
  return Image.fromarray(image_np), confidence, label
219
 
220
- # App title
221
  st.markdown("<h1 style='text-align: center;'>😷 AI Face Mask Detection System</h1>", unsafe_allow_html=True)
222
  st.markdown("<p style='text-align: center;'>Upload or capture an image to analyze mask presence.</p>", unsafe_allow_html=True)
223
 
224
  # Input choice
225
  input_choice = st.selectbox("Choose Input Method", ["πŸ“€ Upload Image", "πŸ“· Use Webcam"])
226
 
 
227
  if input_choice == "πŸ“€ Upload Image":
228
  uploaded_file = st.file_uploader("Choose an image file", type=["jpg", "jpeg", "png"])
229
-
230
  if uploaded_file:
231
- col1, col2 = st.columns(2)
232
- image_input = resize_image(Image.open(uploaded_file))
233
 
234
- # Convert to NumPy and resize with OpenCV
235
- image_np = np.array(image_input)
236
- resized_img = cv2.resize(image_np, (400, 400))
237
- resized_img_rgb = cv2.cvtColor(resized_img, cv2.COLOR_BGR2RGB)
238
 
239
  with col1:
240
- st.image(resized_img_rgb, caption="Uploaded Image")
241
 
242
  with st.spinner("Analyzing with AI model..."):
243
  result_img, confidence, label = detect_and_predict(image_input)
244
 
245
  with col2:
246
- resized_output = result_img.resize((400, 400))
247
- st.image(resized_output, caption="Detection Output")
248
-
249
  if confidence is not None:
250
  st.metric("Confidence Score", f"{confidence*100:.2f}%")
251
  st.success(label) if "Mask" in label else st.error(label)
252
  else:
253
  st.warning(label)
254
 
 
255
  elif input_choice == "πŸ“· Use Webcam":
256
  col1, col2 = st.columns([1, 3])
257
 
@@ -259,16 +108,13 @@ elif input_choice == "πŸ“· Use Webcam":
259
  camera_image = st.camera_input("Take a picture using webcam")
260
 
261
  if camera_image:
262
- image_input = resize_image(Image.open(camera_image))
263
 
264
  with st.spinner("Analyzing..."):
265
  result_img, confidence, label = detect_and_predict(image_input)
266
 
267
  with col2:
268
- st.write("Resulted Image")
269
- resized_output = result_img.resize((400, 400))
270
- st.image(resized_output, caption="Detection Output")
271
-
272
  if confidence is not None:
273
  st.metric("Confidence Score", f"{confidence*100:.2f}%")
274
  st.success(label) if "Mask" in label else st.error(label)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  import numpy as np
3
  import cv2
 
22
  # Haar Cascade for face detection
23
  face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
24
 
25
+ # Sidebar
26
  with st.sidebar:
27
  st.title("🧠 About This App")
28
  st.markdown("""
 
36
  st.markdown("---")
37
  st.caption("πŸ“ Developed by Surendra β€’ 2025")
38
 
39
+ # Optional resize function (only for uploads)
40
  def resize_image(image, max_size=(400, 400)):
41
  image = image.copy()
42
+ image.thumbnail(max_size) # maintains aspect ratio
43
  return image
44
 
45
  # Detection function
 
61
  confidence = (1 - prediction) if prediction < 0.5 else prediction
62
  label = "βœ… Mask Detected" if prediction < 0.5 else "🚫 No Mask Detected"
63
 
64
+ # Draw results on original image
65
  color = (0, 255, 0) if prediction < 0.5 else (255, 0, 0)
66
  cv2.rectangle(image_np, (x, y), (x + w, y + h), color, 2)
67
  cv2.putText(image_np, f"{label} ({confidence*100:.2f}%)", (x, y - 10),
 
69
 
70
  return Image.fromarray(image_np), confidence, label
71
 
72
+ # App header
73
  st.markdown("<h1 style='text-align: center;'>😷 AI Face Mask Detection System</h1>", unsafe_allow_html=True)
74
  st.markdown("<p style='text-align: center;'>Upload or capture an image to analyze mask presence.</p>", unsafe_allow_html=True)
75
 
76
  # Input choice
77
  input_choice = st.selectbox("Choose Input Method", ["πŸ“€ Upload Image", "πŸ“· Use Webcam"])
78
 
79
+ # === Upload Image ===
80
  if input_choice == "πŸ“€ Upload Image":
81
  uploaded_file = st.file_uploader("Choose an image file", type=["jpg", "jpeg", "png"])
82
+
83
  if uploaded_file:
84
+ image_input = Image.open(uploaded_file)
85
+ resized_display = resize_image(image_input)
86
 
87
+ col1, col2 = st.columns(2)
 
 
 
88
 
89
  with col1:
90
+ st.image(resized_display, caption="Uploaded Image")
91
 
92
  with st.spinner("Analyzing with AI model..."):
93
  result_img, confidence, label = detect_and_predict(image_input)
94
 
95
  with col2:
96
+ st.image(result_img, caption="Detection Output")
 
 
97
  if confidence is not None:
98
  st.metric("Confidence Score", f"{confidence*100:.2f}%")
99
  st.success(label) if "Mask" in label else st.error(label)
100
  else:
101
  st.warning(label)
102
 
103
+ # === Webcam Input ===
104
  elif input_choice == "πŸ“· Use Webcam":
105
  col1, col2 = st.columns([1, 3])
106
 
 
108
  camera_image = st.camera_input("Take a picture using webcam")
109
 
110
  if camera_image:
111
+ image_input = Image.open(camera_image)
112
 
113
  with st.spinner("Analyzing..."):
114
  result_img, confidence, label = detect_and_predict(image_input)
115
 
116
  with col2:
117
+ st.image(result_img, caption="Detection Output")
 
 
 
118
  if confidence is not None:
119
  st.metric("Confidence Score", f"{confidence*100:.2f}%")
120
  st.success(label) if "Mask" in label else st.error(label)