Surendradjh commited on
Commit
e0445df
·
verified ·
1 Parent(s): 33d1fe2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -57
app.py CHANGED
@@ -4,128 +4,133 @@ 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.")
 
4
  from PIL import Image
5
  import time
6
  import cvlib as cv
 
7
 
8
+ # Set page config
9
+ st.set_page_config(page_title="Face Mask Detection", layout="wide")
10
+
11
+ # Initialize session state
12
+ if "image_captured" not in st.session_state:
13
+ st.session_state.image_captured = None
14
  if "camera_key" not in st.session_state:
15
  st.session_state.camera_key = str(time.time())
16
 
17
+ # Header
 
18
  st.markdown("<h1 style='text-align: center;'>😷 Face Mask Detection</h1>", unsafe_allow_html=True)
19
  input_method = st.selectbox("Choose Input Method", ["Camera Capture", "Upload Image"])
20
 
21
+ # Dummy mask classifier (for now)
22
+ def classify_face_dummy(face_img):
23
+ mean = np.mean(face_img)
24
+ if mean % 2 < 1:
25
+ return "Mask", 0.90
26
+ else:
27
+ return "No Mask", 0.60
28
+
29
  def detect_and_classify_faces(img_np):
30
  faces, confidences = cv.detect_face(img_np)
31
  results = []
32
+ for i, face in enumerate(faces):
 
33
  (startX, startY) = face[0], face[1]
34
  (endX, endY) = face[2], face[3]
35
+ face_crop = img_np[startY:endY, startX:endX]
36
 
37
+ if face_crop.size == 0:
38
+ continue
 
 
 
 
 
 
 
39
 
40
+ label, conf = classify_face_dummy(face_crop)
41
  results.append({
42
  "box": [startX, startY, endX - startX, endY - startY],
43
  "label": label,
44
+ "confidence": conf
45
  })
 
46
  return results
47
 
48
+ # Layout
49
  col1, col2 = st.columns(2)
50
 
51
+ # ------------------- CAMERA CAPTURE MODE -------------------
52
  if input_method == "Camera Capture":
53
  with col1:
54
  st.markdown("### 📸 Capturing Image")
 
55
  camera_img = st.camera_input("Take a photo", key=st.session_state.camera_key)
56
 
57
  if camera_img:
58
+ st.session_state.image_captured = camera_img
 
 
59
 
60
+ # Clear Button
61
  if st.button("❌ Clear photo"):
62
+ st.session_state.image_captured = None
63
  st.session_state.camera_key = str(time.time())
64
  st.experimental_rerun()
65
 
66
+ image = Image.open(camera_img)
67
+ st.image(image, caption="Captured Image", use_container_width=True)
68
+
69
+ if st.session_state.image_captured:
70
  with col2:
71
  st.markdown("### 🧠 Detection Result")
72
+ image = Image.open(st.session_state.image_captured)
73
+ img_np = np.array(image)
74
 
75
+ results = detect_and_classify_faces(img_np)
 
 
76
 
77
+ for res in results:
78
+ x, y, w, h = res["box"]
79
+ label = res["label"]
80
+ conf = res["confidence"]
81
  color = (0, 255, 0) if label == "Mask" else (0, 0, 255)
82
 
83
  cv2.rectangle(img_np, (x, y), (x + w, y + h), color, 2)
84
  cv2.putText(img_np, f"{label} ({conf*100:.2f}%)", (x, y - 10),
85
  cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
86
 
87
+ st.image(img_np, caption="Result Image", channels="BGR", use_container_width=True)
88
 
89
+ for i, face in enumerate(results, 1):
 
90
  label_color = "green" if face["label"] == "Mask" else "red"
91
+ st.markdown(
92
+ f"**Face {i}:** <span style='color:{label_color}'>{face['label']}</span> ({face['confidence']*100:.2f}%)",
93
+ unsafe_allow_html=True)
94
 
95
+ if any(face["label"] == "No Mask" for face in results):
96
  st.error("⚠️ One or more people not wearing a mask!")
97
  else:
98
  st.success("✅ All faces have masks.")
99
 
100
+ # ------------------- UPLOAD IMAGE MODE -------------------
101
  elif input_method == "Upload Image":
102
  with col1:
103
+ st.markdown("### 📁 Upload Image")
104
+ uploaded_img = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
105
+ if uploaded_img:
106
+ image = Image.open(uploaded_img)
107
+ st.image(image, caption="Uploaded Image", use_container_width=True)
108
 
109
+ if uploaded_img:
110
  with col2:
111
  st.markdown("### 🧠 Detection Result")
112
+ img_np = np.array(Image.open(uploaded_img))
113
+ results = detect_and_classify_faces(img_np)
114
 
115
+ for res in results:
116
+ x, y, w, h = res["box"]
117
+ label = res["label"]
118
+ conf = res["confidence"]
119
  color = (0, 255, 0) if label == "Mask" else (0, 0, 255)
120
 
121
  cv2.rectangle(img_np, (x, y), (x + w, y + h), color, 2)
122
  cv2.putText(img_np, f"{label} ({conf*100:.2f}%)", (x, y - 10),
123
  cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
124
 
125
+ st.image(img_np, caption="Result Image", channels="BGR", use_container_width=True)
126
 
127
+ for i, face in enumerate(results, 1):
128
  label_color = "green" if face["label"] == "Mask" else "red"
129
+ st.markdown(
130
+ f"**Face {i}:** <span style='color:{label_color}'>{face['label']}</span> ({face['confidence']*100:.2f}%)",
131
+ unsafe_allow_html=True)
132
 
133
+ if any(face["label"] == "No Mask" for face in results):
134
  st.error("⚠️ One or more people not wearing a mask!")
135
  else:
136
  st.success("✅ All faces have masks.")