SURESHBEEKHANI commited on
Commit
2353f19
Β·
verified Β·
1 Parent(s): 7b90fcd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -123
app.py CHANGED
@@ -1,123 +1,107 @@
1
- import streamlit as st
2
- from ultralytics import YOLO
3
- from PIL import Image
4
- import torchvision.transforms as transforms
5
- import base64
6
- import cv2
7
- import numpy as np
8
-
9
- # Set Streamlit Page Configuration
10
- st.set_page_config(
11
- page_title="PPE Detect",
12
- page_icon="logo/logo.png",
13
- layout="centered"
14
- )
15
-
16
- # Cache the YOLO model to optimize performance
17
- @st.cache_resource()
18
- def load_model():
19
- return YOLO("model/best.pt") # Ensure correct model path
20
-
21
- model = load_model()
22
-
23
- # Define image transformation pipeline
24
- transform = transforms.Compose([
25
- transforms.Resize((640, 640)),
26
- transforms.ToTensor()
27
- ])
28
-
29
- # Function to perform PPE detection on images
30
- def predict_ppe(image: Image.Image):
31
- try:
32
- image_tensor = transform(image).unsqueeze(0) # Add batch dimension
33
- results = model.predict(image_tensor)
34
- output_image = results[0].plot() # Overlay predictions
35
- return Image.fromarray(output_image)
36
- except Exception as e:
37
- st.error(f"Prediction Error: {e}")
38
- return None
39
-
40
- # Function to encode image to base64 for embedding
41
- def get_base64_image(image_path):
42
- try:
43
- with open(image_path, "rb") as img_file:
44
- return base64.b64encode(img_file.read()).decode()
45
- except FileNotFoundError:
46
- return None
47
-
48
- # Function for real-time PPE detection using webcam
49
- def live_ppe_detection():
50
- st.sidebar.write("Starting live detection...")
51
- cap = cv2.VideoCapture(0)
52
- if not cap.isOpened():
53
- st.sidebar.error("Error: Could not open webcam.")
54
- return
55
-
56
- stframe = st.empty()
57
- stop_button = st.sidebar.button("Stop Live Detection", key="stop_button")
58
-
59
- while cap.isOpened():
60
- ret, frame = cap.read()
61
- if not ret:
62
- st.sidebar.error("Failed to capture video frame.")
63
- break
64
-
65
- results = model.predict(frame)
66
- output_frame = results[0].plot()
67
- stframe.image(output_frame, channels="BGR")
68
-
69
- if stop_button:
70
- break
71
-
72
- cap.release()
73
- cv2.destroyAllWindows()
74
-
75
- # Display logo
76
- image_base64 = get_base64_image("logo/logo.png")
77
- if image_base64:
78
- st.markdown(
79
- f'<div style="text-align: center;"><img src="data:image/png;base64,{image_base64}" width="100"></div>',
80
- unsafe_allow_html=True
81
- )
82
-
83
- # UI Customization
84
- st.markdown("""
85
- <style>
86
- [data-testid="stSidebar"] { background-color: #1E1E2F; }
87
- [data-testid="stSidebar"] h1, [data-testid="stSidebar"] h2 { color: white; }
88
- h1 { text-align: center; font-size: 36px; font-weight: bold; color: #2C3E50; }
89
- div.stButton > button { background-color: #3498DB; color: white; font-weight: bold; }
90
- div.stButton > button:hover { background-color: #2980B9; }
91
- </style>
92
- """, unsafe_allow_html=True)
93
-
94
- # Sidebar - File Upload
95
- st.sidebar.header("πŸ“€ Upload an Image")
96
- uploaded_file = st.sidebar.file_uploader("Drag and drop or browse", type=['jpg', 'png', 'jpeg'])
97
-
98
- # Sidebar - Live Predictions
99
- st.sidebar.header("πŸ“‘ Live Predictions")
100
- if st.sidebar.button("Start Live Detection", key="start_button"):
101
- live_ppe_detection()
102
-
103
- # Main Page
104
- st.title("PPE Detect")
105
- st.markdown("<p style='text-align: center;'>Detect personal protective equipment (PPE) in images.</p>", unsafe_allow_html=True)
106
-
107
- if uploaded_file:
108
- image = Image.open(uploaded_file).convert("RGB")
109
- col1, col2 = st.columns(2)
110
-
111
- with col1:
112
- st.image(image, caption="πŸ“· Uploaded Image", use_container_width=True)
113
-
114
- if st.sidebar.button("πŸ” Predict PPE", key="predict_button"):
115
- detected_image = predict_ppe(image)
116
- if detected_image:
117
- with col2:
118
- st.image(detected_image, caption="🎯 PPE Detection Result", use_container_width=True)
119
- else:
120
- st.error("Detection failed. Please try again.")
121
-
122
-
123
- st.info("This app uses **YOLO** for PPE detection. Upload an image or start live detection to get started.")
 
1
+ import streamlit as st
2
+ from ultralytics import YOLO
3
+ from PIL import Image
4
+ import torchvision.transforms as transforms
5
+ import base64
6
+ import cv2
7
+ import numpy as np
8
+ from streamlit_webrtc import webrtc_streamer
9
+ import av
10
+
11
+ # Set Streamlit Page Configuration
12
+ st.set_page_config(
13
+ page_title="PPE Detect",
14
+ page_icon="logo/logo.png",
15
+ layout="centered"
16
+ )
17
+
18
+ # Cache the YOLO model to optimize performance
19
+ @st.cache_resource()
20
+ def load_model():
21
+ return YOLO("model/best.pt") # Ensure correct model path
22
+
23
+ model = load_model()
24
+
25
+ # Define image transformation pipeline
26
+ transform = transforms.Compose([
27
+ transforms.Resize((640, 640)),
28
+ transforms.ToTensor()
29
+ ])
30
+
31
+ # Function to perform PPE detection on images
32
+ def predict_ppe(image: Image.Image):
33
+ try:
34
+ image_tensor = transform(image).unsqueeze(0) # Add batch dimension
35
+ results = model.predict(image_tensor)
36
+ output_image = results[0].plot() # Overlay predictions
37
+ return Image.fromarray(output_image)
38
+ except Exception as e:
39
+ st.error(f"Prediction Error: {e}")
40
+ return None
41
+
42
+ # Function to encode image to base64 for embedding
43
+ def get_base64_image(image_path):
44
+ try:
45
+ with open(image_path, "rb") as img_file:
46
+ return base64.b64encode(img_file.read()).decode()
47
+ except FileNotFoundError:
48
+ return None
49
+
50
+ # Function for real-time PPE detection using WebRTC
51
+ def process_frame(frame):
52
+ img = frame.to_ndarray(format="bgr24") # Convert frame to numpy array
53
+ results = model.predict(img) # Run detection
54
+ output_img = results[0].plot() # Draw detection results
55
+ return av.VideoFrame.from_ndarray(output_img, format="bgr24") # Convert back to VideoFrame
56
+
57
+ # Display logo
58
+ image_base64 = get_base64_image("logo/logo.png")
59
+ if image_base64:
60
+ st.markdown(
61
+ f'<div style="text-align: center;"><img src="data:image/png;base64,{image_base64}" width="100"></div>',
62
+ unsafe_allow_html=True
63
+ )
64
+
65
+ # UI Customization
66
+ st.markdown("""
67
+ <style>
68
+ [data-testid="stSidebar"] { background-color: #1E1E2F; }
69
+ [data-testid="stSidebar"] h1, [data-testid="stSidebar"] h2 { color: white; }
70
+ h1 { text-align: center; font-size: 36px; font-weight: bold; color: #2C3E50; }
71
+ div.stButton > button { background-color: #3498DB; color: white; font-weight: bold; }
72
+ div.stButton > button:hover { background-color: #2980B9; }
73
+ </style>
74
+ """, unsafe_allow_html=True)
75
+
76
+ # Sidebar - File Upload
77
+ st.sidebar.header("πŸ“€ Upload an Image")
78
+ uploaded_file = st.sidebar.file_uploader("Drag and drop or browse", type=['jpg', 'png', 'jpeg'])
79
+
80
+ # Sidebar - Live Predictions
81
+ st.sidebar.header("πŸ“‘ Live Predictions")
82
+ st.sidebar.write("Start real-time PPE detection using your webcam")
83
+ webrtc_streamer(key="live", video_frame_callback=process_frame)
84
+
85
+ # Main Page
86
+ st.title("PPE Detect")
87
+ st.markdown("<p style='text-align: center;'>Detect personal protective equipment (PPE) in images.</p>", unsafe_allow_html=True)
88
+
89
+ if uploaded_file:
90
+ image = Image.open(uploaded_file).convert("RGB")
91
+ col1, col2 = st.columns(2)
92
+
93
+ with col1:
94
+ st.image(image, caption="πŸ“· Uploaded Image", use_container_width=True)
95
+
96
+ if st.sidebar.button("πŸ” Predict PPE", key="predict_button"):
97
+ detected_image = predict_ppe(image)
98
+ if detected_image:
99
+ with col2:
100
+ st.image(detected_image, caption="🎯 PPE Detection Result", use_container_width=True)
101
+ else:
102
+ st.error("Detection failed. Please try again.")
103
+
104
+
105
+
106
+
107
+ st.info("This app uses **YOLO** for PPE detection. Upload an image or start live detection to get started.")