DasariHarshitha commited on
Commit
aaa6e33
Β·
verified Β·
1 Parent(s): baedd28

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -21
app.py CHANGED
@@ -5,30 +5,29 @@ from keras.models import load_model
5
  from keras.preprocessing.image import img_to_array
6
  from PIL import Image
7
 
8
- # Set page config
9
- st.set_page_config(page_title="Face Mask Detection", layout="centered")
10
 
11
- # Load model once
12
  @st.cache_resource
13
  def load_model_cached():
14
- return load_model("Face Detector.keras") # Make sure this is trained on cropped face images
15
 
16
  model = load_model_cached()
17
 
18
- # Load Haar Cascade for face detection
19
  face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
20
 
21
- # Function to detect face and predict
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
-
26
  faces = face_cascade.detectMultiScale(gray, 1.1, 4)
27
 
28
  if len(faces) == 0:
29
  return image_input, None, "No face detected"
30
 
31
- x, y, w, h = faces[0] # Just take the first detected face
32
  face_roi = image_np[y:y+h, x:x+w]
33
  face_pil = Image.fromarray(face_roi).resize((200, 200))
34
  img_array = img_to_array(face_pil) / 255.0
@@ -38,32 +37,39 @@ def detect_and_predict(image_input):
38
  confidence = (1 - prediction) if prediction < 0.5 else prediction
39
  label = "βœ… Mask Detected" if prediction < 0.5 else "🚫 No Mask Detected"
40
 
41
- # Draw rectangle and label
42
  color = (0, 255, 0) if prediction < 0.5 else (255, 0, 0)
43
  cv2.rectangle(image_np, (x, y), (x + w, y + h), color, 2)
44
- cv2.putText(image_np, f"{label} ({confidence*100:.2f}%)",(x, y - 10),
45
- cv2.FONT_HERSHEY_SIMPLEX, 0.4, color, 2)
46
 
47
  return Image.fromarray(image_np), confidence, label
48
 
49
- # App UI
50
- st.title("😷 Smart Face Mask Detection App")
51
- st.markdown("Upload a face image or use your webcam to check if a mask is being worn.")
 
 
 
52
 
53
- # Tabs
54
- tab1, tab2 = st.tabs(["πŸ“€ Upload Image", "πŸ“· Use Webcam"])
 
 
 
55
 
 
56
  with tab1:
 
57
  uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
58
  if uploaded_file:
59
  try:
60
  image_input = Image.open(uploaded_file)
61
- st.image(image_input, caption="Uploaded Image", use_container_width=True)
62
 
63
  with st.spinner("Analyzing..."):
64
  result_img, confidence, label = detect_and_predict(image_input)
65
 
66
- st.image(result_img, caption="Detection Result", use_container_width=True)
67
  if confidence is not None:
68
  st.metric("Confidence", f"{confidence*100:.2f}%")
69
  if "Mask" in label:
@@ -76,17 +82,19 @@ with tab1:
76
  except Exception as e:
77
  st.error(f"❌ Error: {str(e)}")
78
 
 
79
  with tab2:
 
80
  camera_image = st.camera_input("Take a picture")
81
  if camera_image:
82
  try:
83
  image_input = Image.open(camera_image)
84
- st.image(image_input, caption="Webcam Snapshot", use_container_width=True)
85
 
86
  with st.spinner("Analyzing..."):
87
  result_img, confidence, label = detect_and_predict(image_input)
88
 
89
- st.image(result_img, caption="Detection Result", use_container_width=True)
90
  if confidence is not None:
91
  st.metric("Confidence", f"{confidence*100:.2f}%")
92
  if "Mask" in label:
@@ -97,4 +105,4 @@ with tab2:
97
  st.warning(label)
98
 
99
  except Exception as e:
100
- st.error(f"❌ Error: {str(e)}")
 
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
 
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.title("😷 Smart Face Mask Detection System")
49
+ st.markdown("""
50
+ ### πŸ“’ Keep yourself and others safe!
51
+ This app allows you to **instantly check if a person is wearing a mask** by uploading an image or using your webcam.
52
+ """)
53
 
54
+ # Tabs with emphasized titles
55
+ tab1, tab2 = st.tabs([
56
+ "πŸ–ΌοΈ **:blue[Upload Image]**",
57
+ "πŸ“· **:green[Use Webcam]**"
58
+ ])
59
 
60
+ # Upload Image Tab
61
  with tab1:
62
+ st.markdown("#### :blue[Upload a photo to detect mask status]")
63
  uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
64
  if uploaded_file:
65
  try:
66
  image_input = Image.open(uploaded_file)
67
+ st.image(image_input, caption="Uploaded Image", width=300)
68
 
69
  with st.spinner("Analyzing..."):
70
  result_img, confidence, label = detect_and_predict(image_input)
71
 
72
+ st.image(result_img, caption="Detection Result", width=300)
73
  if confidence is not None:
74
  st.metric("Confidence", f"{confidence*100:.2f}%")
75
  if "Mask" in label:
 
82
  except Exception as e:
83
  st.error(f"❌ Error: {str(e)}")
84
 
85
+ # Webcam Tab
86
  with tab2:
87
+ st.markdown("#### :green[Take a picture using webcam to detect mask]")
88
  camera_image = st.camera_input("Take a picture")
89
  if camera_image:
90
  try:
91
  image_input = Image.open(camera_image)
92
+ st.image(image_input, caption="Webcam Snapshot", width=300)
93
 
94
  with st.spinner("Analyzing..."):
95
  result_img, confidence, label = detect_and_predict(image_input)
96
 
97
+ st.image(result_img, caption="Detection Result", width=300)
98
  if confidence is not None:
99
  st.metric("Confidence", f"{confidence*100:.2f}%")
100
  if "Mask" in label:
 
105
  st.warning(label)
106
 
107
  except Exception as e:
108
+ st.error(f"❌ Error: {str(e)}")