AbhishekShrimali commited on
Commit
28c4e9f
Β·
verified Β·
1 Parent(s): edac045

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +137 -133
app.py CHANGED
@@ -1,133 +1,137 @@
1
- import os
2
- import cv2
3
- import streamlit as st
4
- from datetime import datetime
5
- from tempfile import NamedTemporaryFile
6
- from ultralytics import YOLO
7
-
8
- # Initialize YOLOv8 model
9
- model = YOLO("best.pt") # Replace with your YOLOv8 model path
10
-
11
- # Output folder for storing detected clips
12
- output_folder = "detected_clips"
13
- os.makedirs(output_folder, exist_ok=True)
14
-
15
- # Initialize session state variables
16
- if "log" not in st.session_state:
17
- st.session_state.log = ""
18
- if "stop_camera" not in st.session_state:
19
- st.session_state.stop_camera = False
20
-
21
- # Streamlit UI
22
- st.title("Weapon Detection System")
23
- st.write("This is a weapon detection system using YOLOv8 and OpenCV.")
24
-
25
- # Placeholder for video feed (Camera Stream)
26
- frame_placeholder = st.empty()
27
-
28
- # Placeholder for logs (⚠ Now defined before use)
29
- log_placeholder = st.empty()
30
-
31
- # Function to write log messages in real-time
32
- def write_log(message):
33
- st.session_state.log += message + "\n"
34
- # Display logs in a scrolling text area
35
- log_placeholder.text_area("Detection Log", value=st.session_state.log, height=300, max_chars=5000, disabled=True)
36
-
37
- # Function to process video feed and detect weapons
38
- def process_video_feed(video_file=None):
39
- st.session_state.stop_camera = False
40
-
41
- # Open webcam or video file
42
- if video_file:
43
- # Save the uploaded video to a temporary file
44
- with NamedTemporaryFile(delete=False, suffix=".mp4") as temp_file:
45
- temp_file.write(video_file.read())
46
- temp_file_path = temp_file.name
47
-
48
- cap = cv2.VideoCapture(temp_file_path)
49
- else:
50
- cap = cv2.VideoCapture(0)
51
-
52
- if not cap.isOpened():
53
- st.error("Error opening camera")
54
- return
55
-
56
- recording = False
57
- out = None
58
-
59
- stop_button = st.button("πŸ›‘ Stop Camera Feed") # Stop button
60
-
61
- while not st.session_state.stop_camera:
62
- ret, frame = cap.read()
63
- if not ret:
64
- break
65
-
66
- # Run YOLOv8 inference
67
- results = model(frame, verbose=False)
68
- annotated_frame = results[0].plot()
69
-
70
- detected = False
71
- weapon_name = ""
72
- now = datetime.now()
73
-
74
- # Check for weapon detection
75
- for result in results[0].boxes:
76
- class_id = int(result.cls[0])
77
- confidence = float(result.conf[0])
78
- if class_id == 0 and confidence > 0.5:
79
- detected = True
80
- weapon_name = "Weapon"
81
- break
82
-
83
- # If weapon detected, start saving the video
84
- if detected:
85
- if not recording:
86
- formatted_date = now.strftime("%d-%m-%y")
87
- formatted_time = now.strftime("%H-%M-%S")
88
- output_video_path = os.path.join(output_folder, f"{weapon_name}_Date_{formatted_date}_Time_{formatted_time}.mp4")
89
-
90
- fourcc = cv2.VideoWriter_fourcc(*"mp4v")
91
- out = cv2.VideoWriter(output_video_path, fourcc, 30, (frame.shape[1], frame.shape[0]))
92
-
93
- if not out.isOpened():
94
- st.error(f"Error opening video writer for {output_video_path}")
95
- break
96
-
97
- recording = True
98
- write_log(f"πŸŽ₯ Recording started for {output_video_path}")
99
-
100
- out.write(frame)
101
-
102
- # Add detection log
103
- timestamp = now.strftime("%d/%m/%y %I:%M:%S %p")
104
- write_log(f"⚠️ {weapon_name} detected at {timestamp}")
105
-
106
- else:
107
- if recording:
108
- recording = False
109
- out.release()
110
- write_log(f"πŸ“ Recording stopped for {output_video_path}")
111
-
112
- # Convert frame to RGB and display in Streamlit
113
- annotated_frame = cv2.cvtColor(annotated_frame, cv2.COLOR_BGR2RGB)
114
- frame_placeholder.image(annotated_frame, channels="RGB", use_container_width=True)
115
-
116
- if stop_button:
117
- st.session_state.stop_camera = True
118
- break
119
-
120
- cap.release()
121
- if recording and out:
122
- out.release()
123
-
124
- # File upload component
125
- video_file = st.file_uploader("πŸ“‚ Upload Video", type=["mp4", "avi", "mov"])
126
-
127
- # Start Camera Feed Button
128
- if not video_file and st.button("πŸŽ₯ Start Camera Feed"):
129
- process_video_feed()
130
-
131
- # Process uploaded video
132
- if video_file:
133
- process_video_feed(video_file)
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import streamlit as st
4
+ from datetime import datetime
5
+ from tempfile import NamedTemporaryFile
6
+ from ultralytics import YOLO
7
+ import os
8
+ os.system("pip install opencv-python")
9
+ import cv2
10
+
11
+
12
+ # Initialize YOLOv8 model
13
+ model = YOLO("best.pt") # Replace with your YOLOv8 model path
14
+
15
+ # Output folder for storing detected clips
16
+ output_folder = "detected_clips"
17
+ os.makedirs(output_folder, exist_ok=True)
18
+
19
+ # Initialize session state variables
20
+ if "log" not in st.session_state:
21
+ st.session_state.log = ""
22
+ if "stop_camera" not in st.session_state:
23
+ st.session_state.stop_camera = False
24
+
25
+ # Streamlit UI
26
+ st.title("Weapon Detection System")
27
+ st.write("This is a weapon detection system using YOLOv8 and OpenCV.")
28
+
29
+ # Placeholder for video feed (Camera Stream)
30
+ frame_placeholder = st.empty()
31
+
32
+ # Placeholder for logs (⚠ Now defined before use)
33
+ log_placeholder = st.empty()
34
+
35
+ # Function to write log messages in real-time
36
+ def write_log(message):
37
+ st.session_state.log += message + "\n"
38
+ # Display logs in a scrolling text area
39
+ log_placeholder.text_area("Detection Log", value=st.session_state.log, height=300, max_chars=5000, disabled=True)
40
+
41
+ # Function to process video feed and detect weapons
42
+ def process_video_feed(video_file=None):
43
+ st.session_state.stop_camera = False
44
+
45
+ # Open webcam or video file
46
+ if video_file:
47
+ # Save the uploaded video to a temporary file
48
+ with NamedTemporaryFile(delete=False, suffix=".mp4") as temp_file:
49
+ temp_file.write(video_file.read())
50
+ temp_file_path = temp_file.name
51
+
52
+ cap = cv2.VideoCapture(temp_file_path)
53
+ else:
54
+ cap = cv2.VideoCapture(0)
55
+
56
+ if not cap.isOpened():
57
+ st.error("Error opening camera")
58
+ return
59
+
60
+ recording = False
61
+ out = None
62
+
63
+ stop_button = st.button("πŸ›‘ Stop Camera Feed") # Stop button
64
+
65
+ while not st.session_state.stop_camera:
66
+ ret, frame = cap.read()
67
+ if not ret:
68
+ break
69
+
70
+ # Run YOLOv8 inference
71
+ results = model(frame, verbose=False)
72
+ annotated_frame = results[0].plot()
73
+
74
+ detected = False
75
+ weapon_name = ""
76
+ now = datetime.now()
77
+
78
+ # Check for weapon detection
79
+ for result in results[0].boxes:
80
+ class_id = int(result.cls[0])
81
+ confidence = float(result.conf[0])
82
+ if class_id == 0 and confidence > 0.5:
83
+ detected = True
84
+ weapon_name = "Weapon"
85
+ break
86
+
87
+ # If weapon detected, start saving the video
88
+ if detected:
89
+ if not recording:
90
+ formatted_date = now.strftime("%d-%m-%y")
91
+ formatted_time = now.strftime("%H-%M-%S")
92
+ output_video_path = os.path.join(output_folder, f"{weapon_name}_Date_{formatted_date}_Time_{formatted_time}.mp4")
93
+
94
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
95
+ out = cv2.VideoWriter(output_video_path, fourcc, 30, (frame.shape[1], frame.shape[0]))
96
+
97
+ if not out.isOpened():
98
+ st.error(f"Error opening video writer for {output_video_path}")
99
+ break
100
+
101
+ recording = True
102
+ write_log(f"πŸŽ₯ Recording started for {output_video_path}")
103
+
104
+ out.write(frame)
105
+
106
+ # Add detection log
107
+ timestamp = now.strftime("%d/%m/%y %I:%M:%S %p")
108
+ write_log(f"⚠️ {weapon_name} detected at {timestamp}")
109
+
110
+ else:
111
+ if recording:
112
+ recording = False
113
+ out.release()
114
+ write_log(f"πŸ“ Recording stopped for {output_video_path}")
115
+
116
+ # Convert frame to RGB and display in Streamlit
117
+ annotated_frame = cv2.cvtColor(annotated_frame, cv2.COLOR_BGR2RGB)
118
+ frame_placeholder.image(annotated_frame, channels="RGB", use_container_width=True)
119
+
120
+ if stop_button:
121
+ st.session_state.stop_camera = True
122
+ break
123
+
124
+ cap.release()
125
+ if recording and out:
126
+ out.release()
127
+
128
+ # File upload component
129
+ video_file = st.file_uploader("πŸ“‚ Upload Video", type=["mp4", "avi", "mov"])
130
+
131
+ # Start Camera Feed Button
132
+ if not video_file and st.button("πŸŽ₯ Start Camera Feed"):
133
+ process_video_feed()
134
+
135
+ # Process uploaded video
136
+ if video_file:
137
+ process_video_feed(video_file)