Spaces:
Sleeping
Sleeping
import streamlit as st | |
import cv2 | |
import time | |
# Initialize session state | |
if "show_button" not in st.session_state: | |
st.session_state.show_button = True | |
if "camera_active" not in st.session_state: | |
st.session_state.camera_active = False | |
class Camera_View: | |
def __init__(self, app, model): | |
self.app = app | |
self.model = model | |
def toggle_camera(self): | |
st.session_state.camera_active = True | |
st.session_state.show_button = False # Hide st.camera_input when camera is started | |
def stop_camera(self): | |
st.session_state.camera_active = False | |
def show(self): | |
# Top navigation | |
col1_back, col2_back = st.columns([0.2, 0.8]) | |
with col1_back: | |
if st.button("Back", key='upload_back', icon=':material/arrow_back:', type='primary'): | |
self.app.change_page("Main") | |
st.markdown("<h1 style='text-align: center;'>🧠 Real-time Detection</h1>", unsafe_allow_html=True) | |
st.divider() | |
# Buttons to control camera | |
col1_button, col2_button = st.columns(2) | |
with col1_button: | |
st.button("Stop Camera", | |
icon=':material/videocam_off:', | |
type='secondary', | |
on_click=self.stop_camera) # Button to stop video | |
with col2_button: | |
st.button("Start Camera", | |
icon=':material/videocam:', | |
type='primary', | |
on_click=self.toggle_camera) | |
# Display st.camera_input if camera is not started yet | |
if st.session_state.show_button: | |
st.camera_input("") | |
frame_placeholder = st.empty() | |
# Run real-time detection if camera is active | |
if st.session_state.camera_active: | |
cap = cv2.VideoCapture(0) | |
while cap.isOpened(): | |
ret, frame = cap.read() | |
if not ret or not st.session_state.camera_active: | |
break | |
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) | |
results = self.model(frame)[0] | |
for result in results.boxes.data.tolist(): | |
x1, y1, x2, y2, score, class_id = result | |
color = (0, 0, 255) if score > 0.5 else (0, 255, 0) | |
cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), color, 2) | |
frame_placeholder.image(frame, channels="RGB", use_container_width=True) | |
time.sleep(0.1) | |
cap.release() | |
st.warning("Camera stopped.") |