Surendradjh commited on
Commit
a42e93f
Β·
verified Β·
1 Parent(s): 91d76df

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -53
app.py CHANGED
@@ -15,43 +15,50 @@ def load_model_cached():
15
  model = load_model_cached()
16
  face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
17
 
18
- def detect_and_predict(image_input):
 
19
  image_np = np.array(image_input.convert("RGB"))
20
  gray = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY)
21
  faces = face_cascade.detectMultiScale(gray, 1.1, 4)
22
 
 
23
  if len(faces) == 0:
24
- return image_input, None, "No face detected"
25
-
26
- x, y, w, h = faces[0]
27
- face_roi = image_np[y:y+h, x:x+w]
28
- face_pil = Image.fromarray(face_roi).resize((200, 200))
29
- img_array = img_to_array(face_pil) / 255.0
30
- img_array = np.expand_dims(img_array, axis=0)
31
-
32
- prediction = model.predict(img_array)[0][0]
33
- confidence = (1 - prediction) if prediction < 0.5 else prediction
34
- label_text = "Mask Detected" if prediction < 0.5 else "No Mask Detected"
35
-
36
- color = (0, 255, 0) if prediction < 0.5 else (0, 0, 255)
37
- cv2.rectangle(image_np, (x, y), (x + w, y + h), color, 2)
38
- cv2.putText(image_np, f"{label_text} ({confidence*100:.2f}%)", (x, y - 10),
39
- cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
40
-
41
- return Image.fromarray(image_np), confidence, label_text
42
-
43
- # Init session states
 
 
 
 
 
 
 
 
 
 
44
  if "captured_image" not in st.session_state:
45
  st.session_state["captured_image"] = None
46
- if "show_camera" not in st.session_state:
47
- st.session_state["show_camera"] = True
48
-
49
- st.title("😷 Face Mask Detection")
50
 
51
- # Input source selection
52
  input_method = st.selectbox("Choose Input Method", ["Upload Image", "Camera Capture"])
53
 
54
- # Upload Image
55
  if input_method == "Upload Image":
56
  uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
57
  if uploaded_file:
@@ -59,53 +66,48 @@ if input_method == "Upload Image":
59
  st.image(image_input, caption="Uploaded Image", use_container_width=True)
60
 
61
  with st.spinner("Analyzing..."):
62
- result_img, confidence, label = detect_and_predict(image_input)
63
 
64
  st.markdown("### 🧠 Detection Result")
65
  st.image(result_img, caption="Result Image", use_container_width=True)
66
- st.metric("Confidence", f"{confidence*100:.2f}%" if confidence else "N/A")
67
 
68
- # βœ… FIXED clean conditional
69
- if label == "Mask Detected":
70
- st.success(label)
71
- elif label == "No Mask Detected":
72
- st.error(label)
73
- else:
74
- st.warning(label)
75
 
76
- # Camera Capture
77
  elif input_method == "Camera Capture":
78
  col1, col2 = st.columns(2)
79
 
80
  with col1:
81
- # Show camera input
82
- if st.session_state["show_camera"]:
 
83
  camera_image = st.camera_input("Take a photo")
84
  if camera_image:
85
  st.session_state["captured_image"] = Image.open(camera_image)
86
- st.session_state["show_camera"] = False # Hide camera after capture
87
  else:
88
  st.image(st.session_state["captured_image"], caption="Captured Image", use_container_width=True)
89
  if st.button("πŸ” Retake"):
90
- # RESET: clear and reopen camera
91
  st.session_state["captured_image"] = None
92
- st.session_state["show_camera"] = True
93
 
94
  with col2:
 
95
  if st.session_state["captured_image"]:
96
  with st.spinner("Analyzing..."):
97
- result_img, confidence, label = detect_and_predict(st.session_state["captured_image"])
98
 
99
- st.markdown("### 🧠 Detection Result")
100
  st.image(result_img, caption="Result Image", use_container_width=True)
101
- st.metric("Confidence", f"{confidence*100:.2f}%" if confidence else "N/A")
102
 
103
- # βœ… FIXED label output
104
- if label == "Mask Detected":
105
- st.success(label)
106
- elif label == "No Mask Detected":
107
- st.error(label)
108
- else:
109
- st.warning(label)
110
  else:
111
- st.info("πŸ“· Waiting for image capture...")
 
15
  model = load_model_cached()
16
  face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
17
 
18
+ # Analyze all detected faces
19
+ def detect_faces_and_predict_all(image_input):
20
  image_np = np.array(image_input.convert("RGB"))
21
  gray = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY)
22
  faces = face_cascade.detectMultiScale(gray, 1.1, 4)
23
 
24
+ results = []
25
  if len(faces) == 0:
26
+ return image_input, results, "No face detected"
27
+
28
+ for (x, y, w, h) in faces:
29
+ face_roi = image_np[y:y + h, x:x + w]
30
+ face_pil = Image.fromarray(face_roi).resize((200, 200))
31
+ img_array = img_to_array(face_pil) / 255.0
32
+ img_array = np.expand_dims(img_array, axis=0)
33
+
34
+ prediction = model.predict(img_array)[0][0]
35
+ confidence = (1 - prediction) if prediction < 0.5 else prediction
36
+ label_text = "Mask Detected" if prediction < 0.5 else "No Mask Detected"
37
+ color = (0, 255, 0) if prediction < 0.5 else (255, 0, 0)
38
+
39
+ # Draw on image
40
+ cv2.rectangle(image_np, (x, y), (x + w, y + h), color, 2)
41
+ cv2.putText(image_np, f"{label_text} ({confidence*100:.2f}%)", (x, y - 10),
42
+ cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
43
+
44
+ results.append({
45
+ "label": label_text,
46
+ "confidence": confidence,
47
+ "position": (x, y, w, h),
48
+ "color": color
49
+ })
50
+
51
+ return Image.fromarray(image_np), results, f"{len(results)} face(s) detected"
52
+
53
+ # Session states
54
+ if "mode" not in st.session_state:
55
+ st.session_state["mode"] = "waiting"
56
  if "captured_image" not in st.session_state:
57
  st.session_state["captured_image"] = None
 
 
 
 
58
 
59
+ st.markdown("## 😁 Face Mask Detection")
60
  input_method = st.selectbox("Choose Input Method", ["Upload Image", "Camera Capture"])
61
 
 
62
  if input_method == "Upload Image":
63
  uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
64
  if uploaded_file:
 
66
  st.image(image_input, caption="Uploaded Image", use_container_width=True)
67
 
68
  with st.spinner("Analyzing..."):
69
+ result_img, faces_data, label = detect_faces_and_predict_all(image_input)
70
 
71
  st.markdown("### 🧠 Detection Result")
72
  st.image(result_img, caption="Result Image", use_container_width=True)
 
73
 
74
+ for i, face in enumerate(faces_data):
75
+ st.markdown(f"**Face {i+1}**: `{face['label']}` ({face['confidence']*100:.2f}%)")
76
+ if face['label'] == "Mask Detected":
77
+ st.success(face['label'])
78
+ else:
79
+ st.error(face['label'])
 
80
 
 
81
  elif input_method == "Camera Capture":
82
  col1, col2 = st.columns(2)
83
 
84
  with col1:
85
+ st.markdown("### πŸ“· Capturing Image")
86
+
87
+ if st.session_state["mode"] == "waiting":
88
  camera_image = st.camera_input("Take a photo")
89
  if camera_image:
90
  st.session_state["captured_image"] = Image.open(camera_image)
91
+ st.session_state["mode"] = "captured"
92
  else:
93
  st.image(st.session_state["captured_image"], caption="Captured Image", use_container_width=True)
94
  if st.button("πŸ” Retake"):
 
95
  st.session_state["captured_image"] = None
96
+ st.session_state["mode"] = "waiting"
97
 
98
  with col2:
99
+ st.markdown("### 🧠 Detection Result")
100
  if st.session_state["captured_image"]:
101
  with st.spinner("Analyzing..."):
102
+ result_img, faces_data, label = detect_faces_and_predict_all(st.session_state["captured_image"])
103
 
 
104
  st.image(result_img, caption="Result Image", use_container_width=True)
 
105
 
106
+ for i, face in enumerate(faces_data):
107
+ st.markdown(f"**Face {i+1}**: `{face['label']}` ({face['confidence']*100:.2f}%)")
108
+ if face['label'] == "Mask Detected":
109
+ st.success(face['label'])
110
+ else:
111
+ st.error(face['label'])
 
112
  else:
113
+ st.info("πŸ“· Waiting for photo capture...")