Surendradjh commited on
Commit
818c8e3
·
verified ·
1 Parent(s): a5b05e7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -86
app.py CHANGED
@@ -3,145 +3,129 @@ import cv2
3
  import numpy as np
4
  from PIL import Image
5
  import time
 
 
6
 
7
- # Set app layout
8
- st.set_page_config(page_title="Face Mask Detection", layout="wide")
9
- st.markdown("<h1 style='text-align: center;'>😷 Face Mask Detection</h1>", unsafe_allow_html=True)
10
-
11
- # Input method selection
12
- input_method = st.selectbox("Choose Input Method", ["Camera Capture", "Upload Image"])
13
-
14
- # ---------- Simulated Face Detection Function (Replace with real model) ----------
15
- def detect_faces(img):
16
- # Dummy example — replace this with real detection logic
17
- height, width = img.shape[:2]
18
- return [
19
- {
20
- "box": [int(width * 0.3), int(height * 0.3), 150, 150],
21
- "label": "No Mask",
22
- "confidence": 0.65
23
- },
24
- {
25
- "box": [int(width * 0.65), int(height * 0.25), 130, 130],
26
- "label": "Mask",
27
- "confidence": 0.88
28
- }
29
- ]
30
- # ----------------------------------------------------------------------------------
31
-
32
- # Session state variables
33
  if "camera_image" not in st.session_state:
34
  st.session_state.camera_image = None
35
  if "camera_key" not in st.session_state:
36
  st.session_state.camera_key = str(time.time())
37
 
38
- # Layout columns
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  col1, col2 = st.columns(2)
40
 
41
- # Camera Capture
42
  if input_method == "Camera Capture":
43
  with col1:
44
- st.markdown("### 🖼️ Capturing Image")
45
 
46
- # Show webcam input
47
  camera_img = st.camera_input("Take a photo", key=st.session_state.camera_key)
48
 
49
  if camera_img:
50
  st.session_state.camera_image = camera_img
 
 
51
 
52
- # Display captured image
53
- st.image(camera_img, caption="Captured Image", use_column_width=True)
54
-
55
- # Clear button
56
  if st.button("❌ Clear photo"):
57
- # Reset session state and re-trigger camera
58
  st.session_state.camera_image = None
59
  st.session_state.camera_key = str(time.time())
60
  st.experimental_rerun()
61
 
62
- # Process detection if image exists
63
  if st.session_state.camera_image:
64
  with col2:
65
  st.markdown("### 🧠 Detection Result")
66
 
67
  img = Image.open(st.session_state.camera_image)
68
  img_np = np.array(img)
69
-
70
- faces = detect_faces(img_np)
71
 
72
  for face in faces:
73
  x, y, w, h = face["box"]
74
  label = face["label"]
75
- confidence = face["confidence"]
 
76
 
77
- color = (0, 255, 0) if "Mask" in label else (0, 0, 255)
78
  cv2.rectangle(img_np, (x, y), (x + w, y + h), color, 2)
79
- cv2.putText(
80
- img_np,
81
- f"{label} ({confidence*100:.2f}%)",
82
- (x, y - 10),
83
- cv2.FONT_HERSHEY_SIMPLEX,
84
- 0.6,
85
- color,
86
- 2,
87
- )
88
-
89
- st.image(img_np, caption="Result Image", use_column_width=True)
90
-
91
- # Face summary
92
  for i, face in enumerate(faces, 1):
93
- label = face["label"]
94
- confidence = face["confidence"]
95
- label_color = "green" if "Mask" in label else "red"
96
- st.markdown(f"**Face {i}:** <span style='color:{label_color}'>{label}</span> ({confidence*100:.2f}%)", unsafe_allow_html=True)
97
 
98
- # Overall result
99
- if any("No Mask" in face["label"] for face in faces):
100
  st.error("⚠️ One or more people not wearing a mask!")
101
  else:
102
  st.success("✅ All faces have masks.")
103
 
104
- # Upload Image
105
  elif input_method == "Upload Image":
106
- uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
107
- if uploaded_file:
108
- with col1:
109
- st.markdown("### 🖼️ Captured Image")
110
  img = Image.open(uploaded_file)
111
- st.image(img, caption="Uploaded Image", use_column_width=True)
112
 
 
113
  with col2:
114
  st.markdown("### 🧠 Detection Result")
115
- img_np = np.array(img)
116
-
117
- faces = detect_faces(img_np)
118
 
119
  for face in faces:
120
  x, y, w, h = face["box"]
121
  label = face["label"]
122
- confidence = face["confidence"]
 
123
 
124
- color = (0, 255, 0) if "Mask" in label else (0, 0, 255)
125
  cv2.rectangle(img_np, (x, y), (x + w, y + h), color, 2)
126
- cv2.putText(
127
- img_np,
128
- f"{label} ({confidence*100:.2f}%)",
129
- (x, y - 10),
130
- cv2.FONT_HERSHEY_SIMPLEX,
131
- 0.6,
132
- color,
133
- 2,
134
- )
135
-
136
- st.image(img_np, caption="Result Image", use_column_width=True)
137
 
138
  for i, face in enumerate(faces, 1):
139
- label = face["label"]
140
- confidence = face["confidence"]
141
- label_color = "green" if "Mask" in label else "red"
142
- st.markdown(f"**Face {i}:** <span style='color:{label_color}'>{label}</span> ({confidence*100:.2f}%)", unsafe_allow_html=True)
143
 
144
- if any("No Mask" in face["label"] for face in faces):
145
  st.error("⚠️ One or more people not wearing a mask!")
146
  else:
147
  st.success("✅ All faces have masks.")
 
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
+ # Session state handling
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  if "camera_image" not in st.session_state:
11
  st.session_state.camera_image = None
12
  if "camera_key" not in st.session_state:
13
  st.session_state.camera_key = str(time.time())
14
 
15
+ # App setup
16
+ st.set_page_config(page_title="Face Mask Detection", layout="wide")
17
+ st.markdown("<h1 style='text-align: center;'>😷 Face Mask Detection</h1>", unsafe_allow_html=True)
18
+ input_method = st.selectbox("Choose Input Method", ["Camera Capture", "Upload Image"])
19
+
20
+ # Face detection with dummy classifier
21
+ def detect_and_classify_faces(img_np):
22
+ faces, confidences = cv.detect_face(img_np)
23
+ results = []
24
+
25
+ for face in faces:
26
+ (startX, startY) = face[0], face[1]
27
+ (endX, endY) = face[2], face[3]
28
+
29
+ # Simulated mask classification (replace with real model)
30
+ face_img = img_np[startY:endY, startX:endX]
31
+ mean_pixel = np.mean(face_img)
32
+ if mean_pixel % 2 < 1:
33
+ label = "Mask"
34
+ confidence = 0.90
35
+ else:
36
+ label = "No Mask"
37
+ confidence = 0.65
38
+
39
+ results.append({
40
+ "box": [startX, startY, endX - startX, endY - startY],
41
+ "label": label,
42
+ "confidence": confidence
43
+ })
44
+
45
+ return results
46
+
47
+ # Columns
48
  col1, col2 = st.columns(2)
49
 
50
+ # --------------- CAMERA INPUT MODE ---------------
51
  if input_method == "Camera Capture":
52
  with col1:
53
+ st.markdown("### 📸 Capturing Image")
54
 
 
55
  camera_img = st.camera_input("Take a photo", key=st.session_state.camera_key)
56
 
57
  if camera_img:
58
  st.session_state.camera_image = camera_img
59
+ img = Image.open(st.session_state.camera_image)
60
+ st.image(img, caption="Captured Image")
61
 
 
 
 
 
62
  if st.button("❌ Clear photo"):
 
63
  st.session_state.camera_image = None
64
  st.session_state.camera_key = str(time.time())
65
  st.experimental_rerun()
66
 
 
67
  if st.session_state.camera_image:
68
  with col2:
69
  st.markdown("### 🧠 Detection Result")
70
 
71
  img = Image.open(st.session_state.camera_image)
72
  img_np = np.array(img)
73
+ faces = detect_and_classify_faces(img_np)
 
74
 
75
  for face in faces:
76
  x, y, w, h = face["box"]
77
  label = face["label"]
78
+ conf = face["confidence"]
79
+ color = (0, 255, 0) if label == "Mask" else (0, 0, 255)
80
 
 
81
  cv2.rectangle(img_np, (x, y), (x + w, y + h), color, 2)
82
+ cv2.putText(img_np, f"{label} ({conf*100:.2f}%)", (x, y - 10),
83
+ cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
84
+
85
+ st.image(img_np, caption="Result Image", use_container_width=True)
86
+
87
+ # Summary
 
 
 
 
 
 
 
88
  for i, face in enumerate(faces, 1):
89
+ label_color = "green" if face["label"] == "Mask" else "red"
90
+ st.markdown(f"**Face {i}:** <span style='color:{label_color}'>{face['label']}</span> ({face['confidence']*100:.2f}%)", unsafe_allow_html=True)
 
 
91
 
92
+ if any(face["label"] == "No Mask" for face in faces):
 
93
  st.error("⚠️ One or more people not wearing a mask!")
94
  else:
95
  st.success("✅ All faces have masks.")
96
 
97
+ # --------------- UPLOAD IMAGE MODE ---------------
98
  elif input_method == "Upload Image":
99
+ with col1:
100
+ st.markdown("### 📷 Captured Image")
101
+ uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
102
+ if uploaded_file:
103
  img = Image.open(uploaded_file)
104
+ st.image(img, caption="Uploaded Image")
105
 
106
+ if uploaded_file:
107
  with col2:
108
  st.markdown("### 🧠 Detection Result")
109
+ img_np = np.array(Image.open(uploaded_file))
110
+ faces = detect_and_classify_faces(img_np)
 
111
 
112
  for face in faces:
113
  x, y, w, h = face["box"]
114
  label = face["label"]
115
+ conf = face["confidence"]
116
+ color = (0, 255, 0) if label == "Mask" else (0, 0, 255)
117
 
 
118
  cv2.rectangle(img_np, (x, y), (x + w, y + h), color, 2)
119
+ cv2.putText(img_np, f"{label} ({conf*100:.2f}%)", (x, y - 10),
120
+ cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
121
+
122
+ st.image(img_np, caption="Result Image", use_container_width=True)
 
 
 
 
 
 
 
123
 
124
  for i, face in enumerate(faces, 1):
125
+ label_color = "green" if face["label"] == "Mask" else "red"
126
+ st.markdown(f"**Face {i}:** <span style='color:{label_color}'>{face['label']}</span> ({face['confidence']*100:.2f}%)", unsafe_allow_html=True)
 
 
127
 
128
+ if any(face["label"] == "No Mask" for face in faces):
129
  st.error("⚠️ One or more people not wearing a mask!")
130
  else:
131
  st.success("✅ All faces have masks.")