ytrsoymr commited on
Commit
e8c136e
·
verified ·
1 Parent(s): 2ac7509

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +132 -0
app.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Unique Page config
9
+ st.set_page_config(
10
+ page_title="VisionGuard: AI Mask Monitor",
11
+ layout="wide"
12
+ )
13
+
14
+ # Load model with caching
15
+ @st.cache_resource
16
+ def load_model_cached():
17
+ return load_model("project_face_mask_detection.keras")
18
+
19
+ model = load_model_cached()
20
+
21
+ # Haar Cascade for face detection
22
+ face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
23
+
24
+ # Sidebar with your branding
25
+ with st.sidebar:
26
+ st.title("VisionGuard: Mask Monitor")
27
+ st.markdown("""
28
+ **VisionGuard** is a real-time AI system designed to help enforce health safety by detecting face mask compliance from images or webcam input.
29
+
30
+ **How it works:**
31
+ - Upload or capture an image
32
+ - The AI detects face(s) and checks for mask presence
33
+ - Results include confidence and visual feedback
34
+
35
+ This tool was built with a vision to promote public health and awareness using AI.
36
+
37
+ **Built by:** Thirupathirao • 2025
38
+ """)
39
+ st.info("For best results, use clear, front-facing images with good lighting.")
40
+ st.caption("Empowering safety through AI.")
41
+
42
+ # Resize image
43
+ def resize_image(image, max_size=(400, 400)):
44
+ image = image.copy()
45
+ image.thumbnail(max_size)
46
+ return image
47
+
48
+ # Prediction logic
49
+ def detect_and_predict(image_input):
50
+ image_np = np.array(image_input.convert("RGB"))
51
+ gray = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY)
52
+ faces = face_cascade.detectMultiScale(gray, 1.1, 4)
53
+
54
+ if len(faces) == 0:
55
+ return image_input, None, "No face detected"
56
+
57
+ x, y, w, h = faces[0]
58
+ face_roi = image_np[y:y+h, x:x+w]
59
+ face_pil = Image.fromarray(face_roi).resize((200, 200))
60
+ img_array = img_to_array(face_pil) / 255.0
61
+ img_array = np.expand_dims(img_array, axis=0)
62
+
63
+ prediction = model.predict(img_array)[0][0]
64
+ confidence = (1 - prediction) if prediction < 0.5 else prediction
65
+ label = "Mask Detected" if prediction < 0.5 else "No Mask Detected"
66
+
67
+ # Draw results
68
+ color = (0, 255, 0) if prediction < 0.5 else (255, 0, 0)
69
+ cv2.rectangle(image_np, (x, y), (x + w, y + h), color, 2)
70
+ cv2.putText(image_np, f"{label} ({confidence*100:.2f}%)", (x, y - 10),
71
+ cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
72
+
73
+ return Image.fromarray(image_np), confidence, label
74
+
75
+ # App header
76
+ st.markdown("<h1 style='text-align: center;'>VisionGuard: AI Mask Monitor</h1>", unsafe_allow_html=True)
77
+ st.markdown("<p style='text-align: center;'>A deep learning-powered tool for mask detection and safety awareness.</p>", unsafe_allow_html=True)
78
+
79
+ # Input method
80
+ input_choice = st.selectbox("Choose Input Method", ["Upload Image", "Use Webcam"])
81
+
82
+ # Upload option
83
+ if input_choice == "Upload Image":
84
+ uploaded_file = st.file_uploader("Upload an image (JPG, JPEG, PNG)", type=["jpg", "jpeg", "png"])
85
+
86
+ if uploaded_file:
87
+ image_input = Image.open(uploaded_file)
88
+ resized_display = resize_image(image_input)
89
+
90
+ col1, col2 = st.columns(2)
91
+
92
+ with col1:
93
+ st.image(resized_display, caption="Uploaded Image")
94
+
95
+ with st.spinner("Analyzing with VisionGuard..."):
96
+ result_img, confidence, label = detect_and_predict(image_input)
97
+
98
+ with col2:
99
+ st.image(result_img, caption="Detection Output")
100
+ if confidence is not None:
101
+ st.metric("Confidence Score", f"{confidence*100:.2f}%")
102
+ if "Mask" in label:
103
+ st.success("✔️ You're following safety measures!")
104
+ else:
105
+ st.error("⚠️ No mask detected! Please wear a mask in public spaces.")
106
+ else:
107
+ st.warning(label)
108
+
109
+ # Webcam option
110
+ elif input_choice == "Use Webcam":
111
+ col1, col2 = st.columns([1, 3])
112
+
113
+ with col1:
114
+ camera_image = st.camera_input("Take a picture using your webcam")
115
+
116
+ if camera_image:
117
+ image_input = Image.open(camera_image)
118
+
119
+ with st.spinner("Analyzing..."):
120
+ result_img, confidence, label = detect_and_predict(image_input)
121
+
122
+ with col2:
123
+ st.write("Analysis Result")
124
+ st.image(result_img, caption="Detection Output")
125
+ if confidence is not None:
126
+ st.metric("Confidence Score", f"{confidence*100:.2f}%")
127
+ if "Mask" in label:
128
+ st.success("✔️ You're following safety measures!")
129
+ else:
130
+ st.error("⚠️ No mask detected! Please wear a mask in public spaces.")
131
+ else:
132
+ st.warning(label)