deedax commited on
Commit
c12a45b
·
1 Parent(s): c3a3f6e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +280 -0
app.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import tempfile
4
+ import time
5
+ import streamlit as st
6
+ from PIL import Image
7
+ from io import BytesIO
8
+ from ultralytics import YOLO
9
+ from torch.cuda import is_available
10
+
11
+ DEMO_IMAGE = 'demo.jpg'
12
+ DEMO_VIDEO = 'demo.mp4'
13
+ MODEL_PATH = 'mask_check.pt'
14
+ device = '0' if is_available() else 'cpu'
15
+
16
+ pred_dict = {
17
+ 0: 'mask',
18
+ 1: 'no-mask'
19
+ }
20
+ color_dict = {
21
+ 'mask': (0, 255, 0),
22
+ 'no-mask': (0, 0, 255)
23
+ }
24
+
25
+ @st.cache_data()
26
+ def load_model():
27
+ model = YOLO(MODEL_PATH)
28
+ return model
29
+
30
+ def draw_preds(model, image, confidence = 0.25, iou = 0.7):
31
+
32
+ preds = model.predict(image, device = device, conf = confidence, iou = iou)[0]
33
+ boxes = preds.boxes.data.cpu()
34
+
35
+ for box in boxes:
36
+
37
+ x1, y1, x2, y2 = list(map(int, box[:4]))
38
+
39
+ pred_prob = int(box[4] * 100)
40
+ pred_class = pred_dict[int(box[5])]
41
+ pred_text = f"{pred_class}: {pred_prob}%"
42
+
43
+ color = color_dict[pred_class]
44
+ pred_text_size, _ = cv2.getTextSize(pred_text, cv2.FONT_HERSHEY_SIMPLEX, fontScale=1, thickness=2)
45
+ pred_text_position = ((x2+x1)//2 - pred_text_size[0]//2, y1 - pred_text_size[1])
46
+
47
+ cv2.rectangle(image, (x1, y1), (x2, y2), color, 2)
48
+ cv2.putText(image, pred_text, (pred_text_position), cv2.FONT_HERSHEY_SIMPLEX, 1, color, 2)
49
+
50
+ return image, (preds.boxes.cls == 0).sum(), (preds.boxes.cls == 1).sum()
51
+
52
+ st.set_page_config(page_title="Mask Check", page_icon="😷")
53
+ st.title('Mask Check 😷')
54
+ st.sidebar.title('Options')
55
+
56
+ @st.cache_data()
57
+ def image_resize(image, width = None, height = None, inter = cv2.INTER_AREA):
58
+ dim = None
59
+ (h, w) = image.shape[:2]
60
+
61
+ if width is None and height is None:
62
+ return image
63
+
64
+ if width is None:
65
+ r = width / float(w)
66
+ dim = (int(width * r), height)
67
+ else:
68
+ r = width/float(w)
69
+ dim = (width, int(h*r))
70
+
71
+ resized = cv2.resize(image, dim, interpolation = inter)
72
+
73
+ return resized
74
+
75
+ app_mode = st.sidebar.selectbox('Choose the App mode',
76
+ ['About the App', 'Check on Image', 'Check on Video'])
77
+
78
+ st.markdown(
79
+ """
80
+ <style>
81
+ [data-testid = 'stSidebar'][aria-expanded = 'true'] > div:first-child{
82
+ width: 350px
83
+ }
84
+ [data-testid = 'stSidebar'][aria-expanded = 'false'] > div:first-child{
85
+ width: 350px
86
+ margin-left: -350px
87
+ }
88
+ </style>
89
+ """, unsafe_allow_html = True
90
+ )
91
+
92
+ if app_mode == 'About the App':
93
+ st.success('This app is created and maintained by [Deedax Inc.](https://github.com/Daheer)')
94
+ st.markdown(
95
+ """
96
+ The purpose of "Mask Check" is to provide a simple and easy-to-use tool for checking if people in images and videos are wearing face masks
97
+ # Installation
98
+ Simply run
99
+ ` bash setup.sh `
100
+ . This will download model weights, requirements and launch the app
101
+ # Usage
102
+ The application can be run in three distinct modes: Image mode, Video mode, and Webcam mode (which is a subset of Video mode). In Image mode, you upload an image, and the application will automatically detect and return the relevant results.
103
+ \n
104
+ In Video mode, users are able to upload a video file and receive corresponding results. Webcam mode, which is nested within Video mode, enables users to run the model on input data captured directly from a webcam. Outputs from the Video mode and Webcam mode can be saved by checking the 'Record' checkbox.
105
+ # Features
106
+ - Image and Video upload
107
+ - Face detection
108
+ - Mask detection
109
+ - FPS counter
110
+ - Results display
111
+ - Webcam inference
112
+ # Built Using
113
+ - [Python](https://python.org)
114
+ - [YOLOv8](https://ultralytics.com/yolov8)
115
+ - [Roboflow](https://roboflow.com/)
116
+ - [Streamlit](https://streamlit.io/)
117
+ # Details
118
+ - Dataset: With regard to the [dataset](https://universe.roboflow.com/deedaxinc/face-mask-detection-uamjv/browse?queryText=&pageSize=50&startingIndex=0&browseQuery=true), approximately half of the 150+ images were self-collected by myself, using a webcam to capture a wide array of facial expressions and features, including frontal and side-facing poses, wearing sunglasses, hats, and headphones. The remaining images were sourced from the internet and were chosen to represent a diverse range of skin tones and races. To balance out the dataset, which was originally heavily skewed towards male subjects due to the local self-collected data being exclusively male, the additional images were chosen to include a slightly higher proportion of female subjects.
119
+ - Data augmentation: The augmentation techniques employed included a range of carefully chosen image manipulations designed to enhance the dataset's diversity and improve model generalization. Each augmentation was meticulously considered for its potential impact on performance, ensuring that the resulting dataset was both comprehensive and representative of real-world scenarios.
120
+ - Crop: 0% Minimum Zoom, 20% Maximum Zoom
121
+ - Rotation: Between -10° and +10°
122
+ - Blur: Up to 2px
123
+ - Noise: Up to 5% of pixels
124
+ - Cutout: 10 boxes with 8% size each
125
+ - Bounding Box: Brightness: Between -25% and +25%
126
+ - Bounding Box: Exposure: Between -25% and +25%
127
+ - Model selection: The selection of YOLOv8s was based on its state-of-the-art design, combined with its compact size (~20MB) and high level of accuracy
128
+ # Performance
129
+ Results shown below are from training the model using YOLOv8s for 100 epochs. See [notebook](training_mask_check.ipynb)
130
+ """)
131
+ st.image('images/confusion_matrix.png')
132
+ st.image('images/labels.jpg')
133
+ st.image('images/labels_correlogram.jpg')
134
+ st.image('images/PR_curve.png')
135
+ st.image('images/results.png')
136
+ st.markdown("""
137
+ # Limitations
138
+ - Relatively low frame rate of approximately 2 frames per second during video inference.
139
+ # Contact
140
+ Dahir Ibrahim (Deedax Inc) \n
141
+ Email - dahiru.ibrahim@outlook.com \n
142
+ Twitter - https://twitter.com/DeedaxInc \n
143
+ YouTube - https://www.youtube.com/@deedaxinc \n
144
+ Project Link - https://github.com/Daheer/mask-check
145
+ """
146
+ )
147
+ elif app_mode == 'Check on Image':
148
+
149
+ model = load_model()
150
+
151
+ st.sidebar.markdown('---')
152
+
153
+ kpi1, kpi2, kpi3, kpi4 = st.columns(4)
154
+ with kpi2:
155
+ st.markdown('**Masks Detected**')
156
+ kpi2_text = st.markdown('0')
157
+ with kpi3:
158
+ st.markdown('**No Masks Detected**')
159
+ kpi3_text = st.markdown('0')
160
+
161
+ detection_confidence = st.sidebar.slider('Min Detection Confidence', min_value = 0.0, max_value = 1.0, value = 0.25)
162
+ detection_iou = st.sidebar.slider('Min Detection IoU (Intecept Over Union)', min_value = 0.0, max_value = 1.0, value = 0.7)
163
+
164
+ st.sidebar.markdown('---')
165
+
166
+ img_file_buffer = st.sidebar.file_uploader('Upload an Image', type = ['jpg', 'png', 'jpeg'])
167
+ if img_file_buffer:
168
+ buffer = BytesIO(img_file_buffer.read())
169
+ data = np.frombuffer(buffer.getvalue(), dtype=np.uint8)
170
+ image = cv2.imdecode(data, cv2.IMREAD_COLOR)
171
+ else:
172
+ demo_image = DEMO_IMAGE
173
+ image = cv2.imread(demo_image, cv2.IMREAD_COLOR)
174
+
175
+ st.sidebar.text('Original Image')
176
+ st.sidebar.image(image, channels = 'BGR')
177
+
178
+ with st.spinner():
179
+ results = draw_preds(model, image, confidence = detection_confidence, iou = detection_iou)
180
+ out_image = results[0]
181
+ masks = results[1]
182
+ no_masks = results[2]
183
+
184
+ kpi2_text.write(f'<h1 style = "text-align: center; color: green;"> {masks} </h1>', unsafe_allow_html = True)
185
+ kpi3_text.write(f'<h1 style = "text-align: center; color: red;"> {no_masks} </h1>', unsafe_allow_html = True)
186
+
187
+ st.subheader('Output Image')
188
+ st.image(out_image, channels = 'BGR', use_column_width = True)
189
+
190
+ elif app_mode == 'Check on Video':
191
+
192
+ st.set_option('deprecation.showfileUploaderEncoding', False)
193
+
194
+ use_webcam = st.sidebar.button('Use Webcam')
195
+ record = st.sidebar.checkbox('Record Video')
196
+
197
+ if record:
198
+ st.checkbox('Recording', True)
199
+
200
+ st.sidebar.markdown('---')
201
+
202
+ detection_confidence = st.sidebar.slider('Min Detection Confidence', min_value = 0.0, max_value = 1.0, value = 0.25)
203
+ detection_iou = st.sidebar.slider('Min Detection IoU (Intercept Over Union)', min_value = 0.0, max_value = 1.0, value = 0.7)
204
+
205
+ kpi1, kpi2, kpi3 = st.columns(3)
206
+ with kpi1:
207
+ st.markdown('**Frame Rate**')
208
+ kpi1_text = st.markdown('0')
209
+ with kpi2:
210
+ st.markdown('**Masks Detected**')
211
+ kpi2_text = st.markdown('0')
212
+ with kpi3:
213
+ st.markdown('**No Masks Detected**')
214
+ kpi3_text = st.markdown('0')
215
+
216
+ st.sidebar.markdown('---')
217
+
218
+ st.markdown('## Output Video')
219
+
220
+ stframe = st.empty()
221
+ video_file_buffer = st.sidebar.file_uploader('Upload a Video', type = ['mov', 'avi', 'mp4', 'mkv'])
222
+ tffile = tempfile.NamedTemporaryFile(delete = False)
223
+
224
+ if use_webcam:
225
+ vid = cv2.VideoCapture(0)
226
+ else:
227
+ if video_file_buffer:
228
+ tffile.write(video_file_buffer.read())
229
+ vid = cv2.VideoCapture(tffile.name)
230
+ else:
231
+ vid = cv2.VideoCapture(DEMO_VIDEO)
232
+ tffile.name = DEMO_VIDEO
233
+
234
+ width = int(vid.get(cv2.CAP_PROP_FRAME_WIDTH))
235
+ height = int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT))
236
+ fps_input = int(vid.get(cv2.CAP_PROP_FPS))
237
+
238
+ codec = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')
239
+ out = cv2.VideoWriter('output1.mp4', codec, fps_input, (width, height))
240
+
241
+ st.sidebar.text('Input Video')
242
+ st.sidebar.video(tffile.name)
243
+
244
+ fps = 0
245
+ i = 0
246
+ model = load_model()
247
+
248
+ masks = 0
249
+ no_masks = 0
250
+ prevTime = 0
251
+
252
+ while vid.isOpened():
253
+ i += 1
254
+ ret, frame = vid.read()
255
+ if not ret:
256
+ continue
257
+
258
+ results = model.predict(frame, device = device)
259
+ out_image = results[0].plot()
260
+ out_image.flags.writeable = True
261
+ masks = (results[0].boxes.cls == 0).sum()
262
+ no_masks = (results[0].boxes.cls == 1).sum()
263
+
264
+ currTime = time.time()
265
+ fps = 1 / (currTime - prevTime)
266
+ prevTime = currTime
267
+
268
+ kpi1_text.write(f'<h1 style = "text-align: center; color: blue;"> {int(fps)} </h1>', unsafe_allow_html = True)
269
+ kpi2_text.write(f'<h1 style = "text-align: center; color: green;"> {masks} </h1>', unsafe_allow_html = True)
270
+ kpi3_text.write(f'<h1 style = "text-align: center; color: red;"> {no_masks} </h1>', unsafe_allow_html = True)
271
+
272
+ out_image = cv2.resize(out_image, (0, 0), fx = .8, fy = .8)
273
+ out_image = image_resize(image = out_image, width = 640)
274
+
275
+ if record:
276
+ out.write(out_image)
277
+
278
+ stframe.image(out_image, channels = 'BGR', use_column_width = True)
279
+
280
+ vid.release()