File size: 4,747 Bytes
e8c136e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3aafe8
e8c136e
 
 
d3aafe8
 
e8c136e
d3aafe8
e8c136e
 
 
 
d3aafe8
 
e8c136e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3aafe8
e8c136e
d3aafe8
 
e8c136e
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import streamlit as st
import numpy as np
import cv2
from keras.models import load_model
from keras.preprocessing.image import img_to_array
from PIL import Image

# Unique Page config
st.set_page_config(
    page_title="VisionGuard: AI Mask Monitor",
    layout="wide"
)

# Load model with caching
@st.cache_resource
def load_model_cached():
    return load_model("project_face_mask_detection.keras")

model = load_model_cached()

# Haar Cascade for face detection
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")

# Sidebar with your branding
with st.sidebar:
    st.title("VisionGuard: Mask Monitor")
    st.markdown("""
    **VisionGuard** is a real-time system powered by **Convolutional Neural Networks (CNNs)** to help promote public health by detecting face mask compliance.

    **How it works:**
    - Upload or capture an image
    - A CNN-based model detects face(s) and checks for mask presence
    - Results include confidence levels and visual feedback

    This tool was built as a deep learning project to demonstrate practical applications of CNNs in image classification tasks.

    **Built by:** Thirupathirao • 2025
    """)
    st.info("For best results, use clear, front-facing images with good lighting.")
    st.caption("Empowering safety through deep learning.")


# Resize image
def resize_image(image, max_size=(400, 400)):
    image = image.copy()
    image.thumbnail(max_size)
    return image

# Prediction logic
def detect_and_predict(image_input):
    image_np = np.array(image_input.convert("RGB"))
    gray = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.1, 4)

    if len(faces) == 0:
        return image_input, None, "No face detected"

    x, y, w, h = faces[0]
    face_roi = image_np[y:y+h, x:x+w]
    face_pil = Image.fromarray(face_roi).resize((200, 200))
    img_array = img_to_array(face_pil) / 255.0
    img_array = np.expand_dims(img_array, axis=0)

    prediction = model.predict(img_array)[0][0]
    confidence = (1 - prediction) if prediction < 0.5 else prediction
    label = "Mask Detected" if prediction < 0.5 else "No Mask Detected"

    # Draw results
    color = (0, 255, 0) if prediction < 0.5 else (255, 0, 0)
    cv2.rectangle(image_np, (x, y), (x + w, y + h), color, 2)
    cv2.putText(image_np, f"{label} ({confidence*100:.2f}%)", (x, y - 10),
                cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)

    return Image.fromarray(image_np), confidence, label

# App header
st.markdown("<h1 style='text-align: center;'>VisionGuard: AI Mask Monitor</h1>", unsafe_allow_html=True)
st.markdown("<p style='text-align: center;'>A deep learning-powered tool for mask detection and safety awareness.</p>", unsafe_allow_html=True)

# Input method
input_choice = st.selectbox("Choose Input Method", ["Upload Image", "Use Webcam"])

# Upload option
if input_choice == "Upload Image":
    uploaded_file = st.file_uploader("Upload an image (JPG, JPEG, PNG)", type=["jpg", "jpeg", "png"])

    if uploaded_file:
        image_input = Image.open(uploaded_file)
        resized_display = resize_image(image_input)

        col1, col2 = st.columns(2)

        with col1:
            st.image(resized_display, caption="Uploaded Image")

        with st.spinner("Analyzing with VisionGuard..."):
            result_img, confidence, label = detect_and_predict(image_input)

        with col2:
            st.image(result_img, caption="Detection Output")
            if confidence is not None:
                st.metric("Confidence Score", f"{confidence*100:.2f}%")
                if "Mask" in label:
                    st.success("✔️ You're following safety measures!")
                else:
                    st.error("⚠️ No mask detected! Please wear a mask in public spaces.")
            else:
                st.warning(label)

# Webcam option
elif input_choice == "Use Webcam":
    col1, col2 = st.columns([1, 3])

    with col1:
        camera_image = st.camera_input("Take a picture using your webcam")

    if camera_image:
        image_input = Image.open(camera_image)

        with st.spinner("Analyzing..."):
            result_img, confidence, label = detect_and_predict(image_input)

        with col2:
            st.write("Analysis Result")
            st.image(result_img, caption="Detection Output")
            if confidence is not None:
                st.metric("Confidence Score", f"{confidence*100:.2f}%")
                if "Mask" in label:
                    st.error("No mask detected! Please wear a mask in public spaces.")
                else:
                    st.success("You're following safety measures!")

            else:
                st.warning(label)