prahalya commited on
Commit
4b1593d
·
verified ·
1 Parent(s): d112229

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -0
app.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 settings
9
+ st.set_page_config(page_title="Smart Face Mask Scanner", layout="centered")
10
+
11
+ # Load model
12
+ @st.cache_resource
13
+ def load_model_cached():
14
+ return load_model("Face Detector.keras")
15
+
16
+ model = load_model_cached()
17
+
18
+ # Load Haar Cascade
19
+ face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
20
+
21
+ # Detection and Prediction
22
+ def detect_and_predict(image_input):
23
+ image_np = np.array(image_input.convert("RGB"))
24
+ gray = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY)
25
+ faces = face_cascade.detectMultiScale(gray, 1.1, 4)
26
+
27
+ if len(faces) == 0:
28
+ return image_input, None, "No face detected"
29
+
30
+ x, y, w, h = faces[0]
31
+ face_roi = image_np[y:y+h, x:x+w]
32
+ face_pil = Image.fromarray(face_roi).resize((200, 200))
33
+ img_array = img_to_array(face_pil) / 255.0
34
+ img_array = np.expand_dims(img_array, axis=0)
35
+
36
+ prediction = model.predict(img_array)[0][0]
37
+ confidence = (1 - prediction) if prediction < 0.5 else prediction
38
+ label = "✅ Mask Detected" if prediction < 0.5 else "🚫 No Mask Detected"
39
+
40
+ color = (0, 255, 0) if prediction < 0.5 else (255, 0, 0)
41
+ cv2.rectangle(image_np, (x, y), (x + w, y + h), color, 2)
42
+ cv2.putText(image_np, f"{label} ({confidence*100:.2f}%)", (x, y - 10),
43
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
44
+
45
+ return Image.fromarray(image_np), confidence, label
46
+
47
+ # App Header
48
+ st.markdown("<h2>😷 Smart Face Mask Detection App</h2>", unsafe_allow_html=True)
49
+ st.markdown("""
50
+ This app allows you to **instantly check if a person is wearing a mask** by uploading an image or using your webcam.
51
+ """)
52
+
53
+ # Tabs with emphasized titles
54
+ tab1, tab2 = st.tabs([
55
+ "🖼️ **:blue[Upload Image]**",
56
+ "📷 **:green[Use Webcam]**"
57
+ ])
58
+
59
+ # Upload Image Tab
60
+ with tab1:
61
+ st.markdown("#### :blue[Upload a photo to detect mask status]")
62
+ uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
63
+ if uploaded_file:
64
+ try:
65
+ image_input = Image.open(uploaded_file)
66
+ st.image(image_input, caption="Uploaded Image", width=300)
67
+
68
+ with st.spinner("Analyzing..."):
69
+ result_img, confidence, label = detect_and_predict(image_input)
70
+
71
+ st.image(result_img, caption="Detection Result", width=300)
72
+ if confidence is not None:
73
+ st.metric("Confidence", f"{confidence*100:.2f}%")
74
+ if "Mask" in label:
75
+ st.success(label)
76
+ else:
77
+ st.error(label)
78
+ else:
79
+ st.warning(label)
80
+
81
+ except Exception as e:
82
+ st.error(f"❌ Error: {str(e)}")
83
+
84
+ # Webcam Tab
85
+ with tab2:
86
+ st.markdown("#### :green[Take a picture using webcam to detect mask]")
87
+ camera_image = st.camera_input("Take a picture")
88
+ if camera_image:
89
+ try:
90
+ image_input = Image.open(camera_image)
91
+ st.image(image_input, caption="Webcam Snapshot", width=300)
92
+
93
+ with st.spinner("Analyzing..."):
94
+ result_img, confidence, label = detect_and_predict(image_input)
95
+
96
+ st.image(result_img, caption="Detection Result", width=300)
97
+ if confidence is not None:
98
+ st.metric("Confidence", f"{confidence*100:.2f}%")
99
+ if "Mask" in label:
100
+ st.success(label)
101
+ else:
102
+ st.error(label)
103
+ else:
104
+ st.warning(label)
105
+
106
+ except Exception as e:
107
+ st.error(f"❌ Error: {str(e)}")
108
+