ashish6318 commited on
Commit
f7849c6
·
verified ·
1 Parent(s): f8690c6

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +118 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,120 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
1
  import streamlit as st
2
+ from PIL import Image, ImageEnhance
3
+ import numpy as np
4
+ import cv2
5
+ import os
6
+ from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
7
+ from tensorflow.keras.preprocessing.image import img_to_array
8
+ from tensorflow.keras.models import load_model
9
+ import detect_mask_image
10
+
11
+ # Setting custom Page Title and Icon with changed layout and sidebar state
12
+ st.set_page_config(page_title='Face Mask Detector', page_icon='😷', layout='centered', initial_sidebar_state='expanded')
13
+
14
+
15
+ def local_css(file_name):
16
+ """ Method for reading styles.css and applying necessary changes to HTML"""
17
+ with open(file_name) as f:
18
+ st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html=True)
19
+
20
+
21
+ def mask_image():
22
+ global RGB_img
23
+ # load our serialized face detector model from disk
24
+ print("[INFO] loading face detector model...")
25
+ prototxtPath = os.path.sep.join(["face_detector", "deploy.prototxt"])
26
+ weightsPath = os.path.sep.join(["face_detector",
27
+ "res10_300x300_ssd_iter_140000.caffemodel"])
28
+ net = cv2.dnn.readNet(prototxtPath, weightsPath)
29
+
30
+ # load the face mask detector model from disk
31
+ print("[INFO] loading face mask detector model...")
32
+ model = load_model("mask_detector.h5")
33
+
34
+
35
+ # load the input image from disk and grab the image spatial
36
+ # dimensions
37
+ image = cv2.imread("./images/out.jpg")
38
+ (h, w) = image.shape[:2]
39
+
40
+ # construct a blob from the image
41
+ blob = cv2.dnn.blobFromImage(image, 1.0, (300, 300),
42
+ (104.0, 177.0, 123.0))
43
+
44
+ # pass the blob through the network and obtain the face detections
45
+ print("[INFO] computing face detections...")
46
+ net.setInput(blob)
47
+ detections = net.forward()
48
+
49
+ # loop over the detections
50
+ for i in range(0, detections.shape[2]):
51
+ # extract the confidence (i.e., probability) associated with
52
+ # the detection
53
+ confidence = detections[0, 0, i, 2]
54
+
55
+ # filter out weak detections by ensuring the confidence is
56
+ # greater than the minimum confidence
57
+ if confidence > 0.5:
58
+ # compute the (x, y)-coordinates of the bounding box for
59
+ # the object
60
+ box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
61
+ (startX, startY, endX, endY) = box.astype("int")
62
+
63
+ # ensure the bounding boxes fall within the dimensions of
64
+ # the frame
65
+ (startX, startY) = (max(0, startX), max(0, startY))
66
+ (endX, endY) = (min(w - 1, endX), min(h - 1, endY))
67
+
68
+ # extract the face ROI, convert it from BGR to RGB channel
69
+ # ordering, resize it to 224x224, and preprocess it
70
+ face = image[startY:endY, startX:endX]
71
+ face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
72
+ face = cv2.resize(face, (224, 224))
73
+ face = img_to_array(face)
74
+ face = preprocess_input(face)
75
+ face = np.expand_dims(face, axis=0)
76
+
77
+ # pass the face through the model to determine if the face
78
+ # has a mask or not
79
+ (mask, withoutMask) = model.predict(face)[0]
80
+
81
+ # determine the class label and color we'll use to draw
82
+ # the bounding box and text
83
+ label = "Mask" if mask > withoutMask else "No Mask"
84
+ color = (0, 255, 0) if label == "Mask" else (0, 0, 255)
85
+
86
+ # include the probability in the label
87
+ label = "{}: {:.2f}%".format(label, max(mask, withoutMask) * 100)
88
+
89
+ # display the label and bounding box rectangle on the output
90
+ # frame
91
+ cv2.putText(image, label, (startX, startY - 10),
92
+ cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 2)
93
+ cv2.rectangle(image, (startX, startY), (endX, endY), color, 2)
94
+ RGB_img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
95
+ mask_image()
96
+
97
+ def mask_detection():
98
+ local_css("css/styles.css")
99
+ st.markdown('<h1 align="center">😷 Face Mask Detection</h1>', unsafe_allow_html=True)
100
+ activities = ["Image", "Webcam"]
101
+ #st.set_option('deprecation.showfileUploaderEncoding', False)
102
+ st.sidebar.markdown("# Mask Detection on?")
103
+ choice = st.sidebar.selectbox("Choose among the given options:", activities)
104
+
105
+ if choice == 'Image':
106
+ st.markdown('<h2 align="center">Detection on Image</h2>', unsafe_allow_html=True)
107
+ st.markdown("### Upload your image here ⬇")
108
+ image_file = st.file_uploader("", type=['jpg']) # upload image
109
+ if image_file is not None:
110
+ our_image = Image.open(image_file) # making compatible to PIL
111
+ im = our_image.save('./images/out.jpg')
112
+ saved_image = st.image(image_file, caption='', use_column_width=True)
113
+ st.markdown('<h3 align="center">Image uploaded successfully!</h3>', unsafe_allow_html=True)
114
+ if st.button('Process'):
115
+ st.image(RGB_img, use_column_width=True)
116
 
117
+ if choice == 'Webcam':
118
+ st.markdown('<h2 align="center">Detection on Webcam</h2>', unsafe_allow_html=True)
119
+ st.markdown('<h3 align="center">This feature will be available soon!</h3>', unsafe_allow_html=True)
120
+ mask_detection()