Surendradjh commited on
Commit
98f27b5
Β·
verified Β·
1 Parent(s): c99191c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -139
app.py CHANGED
@@ -1,148 +1,115 @@
1
  import streamlit as st
2
- import cv2
3
  import numpy as np
 
 
 
4
  from PIL import Image
5
- import time
6
- import cvlib as cv
7
- from cvlib.object_detection import draw_bbox
8
-
9
- # Set page config
10
- st.set_page_config(page_title="Face Mask Detection", layout="wide")
11
-
12
- # Initialize session state
13
- if "image_captured" not in st.session_state:
14
- st.session_state.image_captured = None
15
- if "camera_key" not in st.session_state:
16
- st.session_state.camera_key = str(time.time())
17
-
18
- # Header
19
- st.markdown("<h1 style='text-align: center;'>😷 Face Mask Detection</h1>", unsafe_allow_html=True)
20
- input_method = st.selectbox("Choose Input Method", ["Camera Capture", "Upload Image"])
21
-
22
- # Dummy classifier (replace this with actual ML model if needed)
23
- def classify_face_dummy(face_img):
24
- mean = np.mean(face_img)
25
- if mean % 2 < 1:
26
- return "Mask", 0.90
27
- else:
28
- return "No Mask", 0.60
29
-
30
- def detect_and_classify_faces(img_np):
31
- # Ensure color format is BGR
32
- if img_np.shape[2] == 3: # 3 channels
33
- img_bgr = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)
34
- else:
35
- img_bgr = img_np
36
-
37
- faces, confidences = cv.detect_face(img_bgr)
38
- results = []
39
-
40
- height, width = img_np.shape[:2]
41
-
42
- for i, face in enumerate(faces):
43
- startX, startY = max(face[0], 0), max(face[1], 0)
44
- endX, endY = min(face[2], width - 1), min(face[3], height - 1)
45
-
46
- face_crop = img_bgr[startY:endY, startX:endX]
47
-
48
- if face_crop.size == 0:
49
- continue
50
-
51
- label, conf = classify_face_dummy(face_crop)
52
- results.append({
53
- "box": [startX, startY, endX - startX, endY - startY],
54
- "label": label,
55
- "confidence": conf
56
- })
57
- return results
58
-
59
- # Layout
60
- col1, col2 = st.columns(2)
61
-
62
- # ------------------- CAMERA CAPTURE MODE -------------------
63
- if input_method == "Camera Capture":
64
- with col1:
65
- st.markdown("### πŸ“Έ Capturing Image")
66
- camera_img = st.camera_input("Take a photo", key=st.session_state.camera_key)
67
-
68
- if camera_img:
69
- st.session_state.image_captured = camera_img
70
-
71
- # Clear Button
72
- if st.button("❌ Clear photo"):
73
- st.session_state.image_captured = None
74
- st.session_state.camera_key = str(time.time())
75
- st.experimental_rerun()
76
-
77
- image = Image.open(camera_img)
78
- st.image(image, caption="Captured Image", use_container_width=True)
79
-
80
- if st.session_state.image_captured:
81
- with col2:
82
- st.markdown("### 🧠 Detection Result")
83
- image = Image.open(st.session_state.image_captured).convert("RGB")
84
- img_np = np.array(image)
85
-
86
- results = detect_and_classify_faces(img_np)
87
 
88
- # Annotate image
89
- for res in results:
90
- x, y, w, h = res["box"]
91
- label = res["label"]
92
- conf = res["confidence"]
93
- color = (0, 255, 0) if label == "Mask" else (0, 0, 255)
94
-
95
- cv2.rectangle(img_np, (x, y), (x + w, y + h), color, 2)
96
- cv2.putText(img_np, f"{label} ({conf*100:.2f}%)", (x, y - 10),
97
- cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
 
99
- st.image(img_np, caption="Result Image", channels="RGB", use_container_width=True)
 
 
 
 
100
 
101
- for i, face in enumerate(results, 1):
102
- label_color = "green" if face["label"] == "Mask" else "red"
103
- st.markdown(
104
- f"**Face {i}:** <span style='color:{label_color}'>{face['label']}</span> ({face['confidence']*100:.2f}%)",
105
- unsafe_allow_html=True)
106
 
107
- if any(face["label"] == "No Mask" for face in results):
108
- st.error("⚠️ One or more people not wearing a mask!")
109
- else:
110
- st.success("βœ… All faces have masks.")
111
-
112
- # ------------------- UPLOAD IMAGE MODE -------------------
113
- elif input_method == "Upload Image":
114
- with col1:
115
- st.markdown("### πŸ“ Upload Image")
116
- uploaded_img = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
117
- if uploaded_img:
118
- image = Image.open(uploaded_img).convert("RGB")
119
- st.image(image, caption="Uploaded Image", use_container_width=True)
120
-
121
- if uploaded_img:
122
  with col2:
123
- st.markdown("### 🧠 Detection Result")
124
- img_np = np.array(image)
125
- results = detect_and_classify_faces(img_np)
126
-
127
- for res in results:
128
- x, y, w, h = res["box"]
129
- label = res["label"]
130
- conf = res["confidence"]
131
- color = (0, 255, 0) if label == "Mask" else (0, 0, 255)
132
-
133
- cv2.rectangle(img_np, (x, y), (x + w, y + h), color, 2)
134
- cv2.putText(img_np, f"{label} ({conf*100:.2f}%)", (x, y - 10),
135
- cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
136
-
137
- st.image(img_np, caption="Result Image", channels="RGB", use_container_width=True)
138
-
139
- for i, face in enumerate(results, 1):
140
- label_color = "green" if face["label"] == "Mask" else "red"
141
- st.markdown(
142
- f"**Face {i}:** <span style='color:{label_color}'>{face['label']}</span> ({face['confidence']*100:.2f}%)",
143
- unsafe_allow_html=True)
144
-
145
- if any(face["label"] == "No Mask" for face in results):
146
- st.error("⚠️ One or more people not wearing a mask!")
147
  else:
148
- st.success("βœ… All faces have masks.")
 
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 with improved UI layout
9
+ st.set_page_config(
10
+ page_title="😷 Smart Face Mask Detection",
11
+ layout="wide",
12
+ page_icon="😷"
13
+ )
14
+
15
+ # Load the 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 for app description and tips
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 YourName β€’ 2025")
38
+
39
+ # Core detection function
40
+ def detect_and_predict(image_input):
41
+ image_np = np.array(image_input.convert("RGB"))
42
+ gray = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY)
43
+ faces = face_cascade.detectMultiScale(gray, 1.1, 4)
44
+
45
+ if len(faces) == 0:
46
+ return image_input, None, "⚠️ No face detected"
47
+
48
+ x, y, w, h = faces[0]
49
+ face_roi = image_np[y:y+h, x:x+w]
50
+ face_pil = Image.fromarray(face_roi).resize((200, 200))
51
+ img_array = img_to_array(face_pil) / 255.0
52
+ img_array = np.expand_dims(img_array, axis=0)
53
+
54
+ prediction = model.predict(img_array)[0][0]
55
+ confidence = (1 - prediction) if prediction < 0.5 else prediction
56
+ label = "βœ… Mask Detected" if prediction < 0.5 else "🚫 No Mask Detected"
57
+
58
+ # Drawing results
59
+ color = (0, 255, 0) if prediction < 0.5 else (255, 0, 0)
60
+ cv2.rectangle(image_np, (x, y), (x + w, y + h), color, 2)
61
+ cv2.putText(image_np, f"{label} ({confidence*100:.2f}%)", (x, y - 10),
62
+ cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
63
+
64
+ return Image.fromarray(image_np), confidence, label
65
+
66
+ # App Title
67
+ st.markdown("<h1 style='text-align: center;'>😷 AI Face Mask Detection System</h1>", unsafe_allow_html=True)
68
+ st.markdown("<p style='text-align: center;'>Upload or capture an image to analyze mask presence.</p>", unsafe_allow_html=True)
69
+
70
+ # Dropdown for choosing input method
71
+ input_choice = st.selectbox("Choose Input Method", ["πŸ“€ Upload Image", "πŸ“· Use Webcam"])
72
+
73
+ if input_choice == "πŸ“€ Upload Image":
74
+ uploaded_file = st.file_uploader("Choose an image file", type=["jpg", "jpeg", "png"])
75
+ if uploaded_file:
76
+ image_input = Image.open(uploaded_file)
77
+ st.image(image_input, caption="Uploaded Image", use_container_width=True)
78
+
79
+ with st.spinner("Analyzing with AI model..."):
80
+ result_img, confidence, label = detect_and_predict(image_input)
81
+
82
+ col1, col2 = st.columns(2)
83
+ with col1:
84
+ st.image(result_img, caption="Detection Output", use_container_width=True)
85
+ with col2:
86
+ if confidence is not None:
87
+ st.metric("Confidence Score", f"{confidence*100:.2f}%")
88
+ if "Mask" in label:
89
+ st.success(label)
90
+ else:
91
+ st.error(label)
92
+ else:
93
+ st.warning(label)
94
 
95
+ elif input_choice == "πŸ“· Use Webcam":
96
+ camera_image = st.camera_input("Take a picture using webcam")
97
+ if camera_image:
98
+ image_input = Image.open(camera_image)
99
+ st.image(image_input, caption="Webcam Snapshot", use_container_width=True)
100
 
101
+ with st.spinner("Analyzing..."):
102
+ result_img, confidence, label = detect_and_predict(image_input)
 
 
 
103
 
104
+ col1, col2 = st.columns(2)
105
+ with col1:
106
+ st.image(result_img, caption="Detection Output", use_container_width=True)
 
 
 
 
 
 
 
 
 
 
 
 
107
  with col2:
108
+ if confidence is not None:
109
+ st.metric("Confidence Score", f"{confidence*100:.2f}%")
110
+ if "Mask" in label:
111
+ st.success(label)
112
+ else:
113
+ st.error(label)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  else:
115
+ st.warning(label)