bushra1dajam commited on
Commit
570c0f0
·
verified ·
1 Parent(s): 2e84f1d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -65
app.py CHANGED
@@ -3,6 +3,14 @@ import cv2
3
  from ultralytics import YOLO
4
  import cvzone
5
  import math
 
 
 
 
 
 
 
 
6
 
7
  # Load the model
8
  model = YOLO('best.pt')
@@ -11,43 +19,118 @@ model = YOLO('best.pt')
11
  classnames = ['Drowsy', 'Awake']
12
 
13
  # Streamlit UI
14
- st.title("Real-Time Drowsiness Detection")
15
-
16
- # Layout
17
- col1, col2 = st.columns(2)
18
-
19
- with col1:
20
- start_button = st.button('Start Webcam')
21
-
22
- with col2:
23
- stop_button = st.button('Stop Webcam')
24
-
25
- stframe = st.empty()
26
- status_text = st.empty()
27
- message_text = st.empty()
28
- alert_sound_placeholder = st.empty() # Placeholder for playing sound
29
-
30
- if start_button:
31
- cap = cv2.VideoCapture(0)
32
- drowsy_count = 0 # Counter for consecutive "Drowsy" detections
33
-
34
- while cap.isOpened():
35
- ret, frame = cap.read()
36
- if not ret:
37
- status_text.write("Failed to grab frame")
38
- break
39
-
40
- frame = cv2.resize(frame, (640, 480))
41
-
42
- # Run the model on the frame
43
- result = model(frame, stream=True)
44
-
45
- # Flag to track if "Drowsy" is detected in this frame
46
- drowsy_detected = False
47
-
48
- # Getting bbox, confidence, and class name information to work with
49
- for info in result:
50
- boxes = info.boxes
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  for box in boxes:
52
  confidence = box.conf[0]
53
  confidence = math.ceil(confidence * 100)
@@ -56,37 +139,12 @@ if start_button:
56
  x1, y1, x2, y2 = box.xyxy[0]
57
  x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
58
  cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 0, 255), 5)
59
- cvzone.putTextRect(frame, f'{classnames[Class]} {confidence}%', [x1 + 8, y1 + 100],
60
- scale=1.5, thickness=2)
61
- if classnames[Class] == 'Drowsy':
62
- drowsy_detected = True
63
-
64
- # Increment the counter if "Drowsy" is detected, otherwise reset the counter
65
- if drowsy_detected:
66
- drowsy_count += 1
67
- status_text.write("Drowsiness detected!")
68
- else:
69
- drowsy_count = 0
70
- status_text.write("Monitoring...")
71
-
72
- # Play alert sound and send message if "Drowsy" is detected 3 or more times
73
- if drowsy_count >= 3:
74
- alert_sound_placeholder.audio('siren-alert-96052.mp3')
75
- message_text.write("**Be careful!** Drowsiness detected multiple times!")
76
- drowsy_count = 0 # Reset the counter after playing the sound
77
 
78
  # Convert image back to RGB for Streamlit
79
  frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
80
 
81
  # Display the image
82
- stframe.image(frame, channels="RGB")
83
-
84
- # Check if stop button is pressed
85
- if stop_button:
86
- break
87
-
88
- cap.release()
89
- status_text.write("Webcam stopped.")
90
- message_text.write("")
91
-
92
 
 
3
  from ultralytics import YOLO
4
  import cvzone
5
  import math
6
+ import pygame
7
+ import numpy as np
8
+
9
+ # Initialize pygame mixer
10
+ pygame.mixer.init()
11
+
12
+ # Load sound
13
+ alert_sound = pygame.mixer.Sound('warning-sound.mp3')
14
 
15
  # Load the model
16
  model = YOLO('best.pt')
 
19
  classnames = ['Drowsy', 'Awake']
20
 
21
  # Streamlit UI
22
+ st.set_page_config(layout="wide") # Set wide layout
23
+
24
+ # Add the logo to the sidebar
25
+ logo_path = "logo.png" # Use the uploaded file path
26
+ st.sidebar.empty() # Add empty space
27
+ st.sidebar.image(logo_path, use_column_width=True)
28
+
29
+ # Create a sidebar for navigation
30
+ st.sidebar.title("Options")
31
+ page = st.sidebar.selectbox("Choose a page", ["Webcam Detection", "Image Upload"])
32
+
33
+ st.title("Drowsiness Detection")
34
+
35
+ if page == "Webcam Detection":
36
+ st.header("Real-Time Drowsiness Detection")
37
+
38
+ # Layout
39
+ col1, col2 = st.columns(2)
40
+
41
+ with col1:
42
+ start_button = st.button('Start Webcam')
43
+
44
+ with col2:
45
+ stop_button = st.button('Stop Webcam')
46
+
47
+ alert_placeholder = st.empty() # Placeholder for alerts
48
+ stframe = st.empty()
49
+ status_text = st.empty()
50
+ message_text = st.empty()
51
+
52
+ if start_button:
53
+ cap = cv2.VideoCapture(0)
54
+ drowsy_count = 0 # Counter for consecutive "Drowsy" detections
55
+
56
+ while cap.isOpened():
57
+ ret, frame = cap.read()
58
+ if not ret:
59
+ status_text.write("Failed to grab frame")
60
+ break
61
+
62
+ frame = cv2.resize(frame, (640, 480))
63
+
64
+ # Run the model on the frame
65
+ result = model(frame, stream=True)
66
+
67
+ # Flag to track if "Drowsy" is detected in this frame
68
+ drowsy_detected = False
69
+
70
+ # Getting bbox, confidence, and class name information to work with
71
+ for info in result:
72
+ boxes = info.boxes
73
+ for box in boxes:
74
+ confidence = box.conf[0]
75
+ confidence = math.ceil(confidence * 100)
76
+ Class = int(box.cls[0])
77
+ if confidence > 50:
78
+ x1, y1, x2, y2 = box.xyxy[0]
79
+ x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
80
+ cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 0, 255), 5)
81
+ cvzone.putTextRect(frame, f'{classnames[Class]} {confidence}%', [x1 + 8, y1 + 100],
82
+ scale=1.5, thickness=2)
83
+ if classnames[Class] == 'Drowsy':
84
+ drowsy_detected = True
85
+
86
+ # Increment the counter if "Drowsy" is detected, otherwise reset the counter
87
+ if drowsy_detected:
88
+ drowsy_count += 1
89
+ status_text.write("Drowsiness detected!")
90
+ else:
91
+ drowsy_count = 0
92
+ status_text.write("Monitoring...")
93
+
94
+ # Play alert sound and send message if "Drowsy" is detected 3 or more times
95
+ if drowsy_count >= 3:
96
+ pygame.mixer.Sound.play(alert_sound)
97
+ alert_placeholder.markdown(
98
+ f'<div style="color: red; font-size: 24px; border: 2px solid red; padding: 10px;">**Be careful! Drowsiness detected!**</div>',
99
+ unsafe_allow_html=True,
100
+ )
101
+ drowsy_count = 0 # Reset the counter after playing the sound
102
+
103
+ # Convert image back to RGB for Streamlit
104
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
105
+
106
+ # Display the image
107
+ stframe.image(frame, channels="RGB")
108
+
109
+ # Check if stop button is pressed
110
+ if stop_button:
111
+ break
112
+
113
+ cap.release()
114
+ status_text.write("Webcam stopped.")
115
+ message_text.write("")
116
+ alert_placeholder.empty()
117
+
118
+ elif page == "Image Upload":
119
+ st.header("Drowsiness Detection on Image")
120
+
121
+ uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
122
+
123
+ if uploaded_file is not None:
124
+ # Read the image
125
+ file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)
126
+ frame = cv2.imdecode(file_bytes, 1)
127
+
128
+ # Perform prediction
129
+ results = model(frame, stream=True)
130
+
131
+ # Process the results
132
+ for result in results:
133
+ boxes = result.boxes
134
  for box in boxes:
135
  confidence = box.conf[0]
136
  confidence = math.ceil(confidence * 100)
 
139
  x1, y1, x2, y2 = box.xyxy[0]
140
  x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
141
  cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 0, 255), 5)
142
+ cv2.putText(frame, f'{classnames[Class]} {confidence}%', (x1 + 8, y1 + 100),
143
+ cv2.FONT_HERSHEY_SIMPLEX, 1.5, (255, 255, 255), 2, cv2.LINE_AA)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
 
145
  # Convert image back to RGB for Streamlit
146
  frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
147
 
148
  # Display the image
149
+ st.image(frame, channels="RGB")
 
 
 
 
 
 
 
 
 
150