jake2004 commited on
Commit
4acc1de
·
verified ·
1 Parent(s): e628cd7

Upload 2 files

Browse files
Files changed (2) hide show
  1. Yolov8/app.py +155 -0
  2. Yolov8/requirements.txt +5 -0
Yolov8/app.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import cv2
3
+ from PIL import Image
4
+ import numpy as np
5
+ from ultralytics import YOLO
6
+ import tempfile # For handling video uploads
7
+ import os
8
+
9
+ # --- Page Configuration ---
10
+ st.set_page_config(
11
+ page_title="Traffic Lane and Object Detection",
12
+ page_icon=":camera_video:",
13
+ layout="wide",
14
+ initial_sidebar_state="expanded",
15
+ )
16
+
17
+ # --- Sidebar ---
18
+ st.sidebar.header("Traffic Lane Detection Options")
19
+ source_type = st.sidebar.radio(
20
+ "Select Input Source:", ("Image", "Video")
21
+ ) # Choose between image and video
22
+ confidence_threshold = st.sidebar.slider(
23
+ "Confidence Threshold", min_value=0.0, max_value=1.0, value=0.25, step=0.05
24
+ )
25
+
26
+ # --- Load YOLO Model ---
27
+ @st.cache_resource # Cache the model for faster loading
28
+ def load_model():
29
+ model = YOLO("yolov8n.pt") # Load a pretrained YOLOv8n model
30
+ return model
31
+
32
+ model = load_model()
33
+
34
+
35
+ # --- Functions ---
36
+ def detect_lanes_and_objects_image(image, model, confidence_threshold):
37
+ """Runs YOLO on a single image."""
38
+ img_np = np.array(image)
39
+ results = model(img_np, conf=confidence_threshold)
40
+
41
+ for result in results:
42
+ boxes = result.boxes
43
+ for box in boxes:
44
+ x1, y1, x2, y2 = map(int, box.xyxy[0].cpu().numpy())
45
+ confidence = box.conf[0].cpu().numpy()
46
+ class_id = int(box.cls[0].cpu().numpy())
47
+
48
+ if confidence > confidence_threshold:
49
+ label = f"{model.names[class_id]} {confidence:.2f}"
50
+ cv2.rectangle(img_np, (x1, y1), (x2, y2), (0, 255, 0), 2)
51
+ cv2.putText(
52
+ img_np,
53
+ label,
54
+ (x1, y1 - 10),
55
+ cv2.FONT_HERSHEY_SIMPLEX,
56
+ 0.5,
57
+ (0, 255, 0),
58
+ 2,
59
+ )
60
+ return img_np
61
+
62
+
63
+ def detect_lanes_and_objects_video(video_path, model, confidence_threshold):
64
+ """Runs YOLO on a video file."""
65
+ video = cv2.VideoCapture(video_path)
66
+ frame_width = int(video.get(3))
67
+ frame_height = int(video.get(4))
68
+ fps = int(video.get(cv2.CAP_PROP_FPS))
69
+ codec = cv2.VideoWriter_fourcc(*"mp4v") # Use appropriate codec for MP4
70
+ output_path = "output.mp4" # Temporary output file
71
+ out = cv2.VideoWriter(output_path, codec, fps, (frame_width, frame_height))
72
+ stframe = st.empty() # Create an empty placeholder in Streamlit
73
+
74
+ while video.isOpened():
75
+ ret, frame = video.read()
76
+ if not ret:
77
+ break
78
+
79
+ results = model(frame, conf=confidence_threshold)
80
+
81
+ for result in results:
82
+ boxes = result.boxes
83
+ for box in boxes:
84
+ x1, y1, x2, y2 = map(int, box.xyxy[0].cpu().numpy())
85
+ confidence = box.conf[0].cpu().numpy()
86
+ class_id = int(box.cls[0].cpu().numpy())
87
+
88
+ if confidence > confidence_threshold:
89
+ label = f"{model.names[class_id]} {confidence:.2f}"
90
+ cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
91
+ cv2.putText(
92
+ frame,
93
+ label,
94
+ (x1, y1 - 10),
95
+ cv2.FONT_HERSHEY_SIMPLEX,
96
+ 0.5,
97
+ (0, 255, 0),
98
+ 2,
99
+ )
100
+
101
+ out.write(frame) # Write the processed frame to the output video
102
+ stframe.image(
103
+ frame, channels="BGR", use_column_width=True
104
+ ) # Display the processed frame in Streamlit
105
+
106
+ video.release()
107
+ out.release()
108
+ cv2.destroyAllWindows()
109
+
110
+ return output_path
111
+
112
+
113
+ # --- Main Application ---
114
+ st.title("Traffic Lane and Object Detection")
115
+
116
+ if source_type == "Image":
117
+ uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
118
+
119
+ if uploaded_file is not None:
120
+ image = Image.open(uploaded_file)
121
+ st.image(image, caption="Uploaded Image", use_column_width=True)
122
+
123
+ if st.button("Run Detection"):
124
+ with st.spinner("Running YOLOv8..."):
125
+ detected_image = detect_lanes_and_objects_image(
126
+ image, model, confidence_threshold
127
+ )
128
+ st.image(detected_image, caption="Detected Image", use_column_width=True)
129
+
130
+ elif source_type == "Video":
131
+ uploaded_video = st.file_uploader("Upload a video", type=["mp4", "avi", "mov"])
132
+
133
+ if uploaded_video is not None:
134
+ # Save the uploaded video to a temporary file
135
+ tfile = tempfile.NamedTemporaryFile(delete=False)
136
+ tfile.write(uploaded_video.read())
137
+ video_path = tfile.name
138
+
139
+ if st.button("Run Detection"):
140
+ with st.spinner("Running YOLOv8 on video..."):
141
+ output_video_path = detect_lanes_and_objects_video(
142
+ video_path, model, confidence_threshold
143
+ )
144
+ st.video(output_video_path)
145
+ # Clean up the temporary file
146
+ tfile.close()
147
+ os.unlink(video_path)
148
+ os.remove(output_video_path) #remove the output video after displaying
149
+
150
+ st.markdown("---")
151
+ st.markdown(
152
+ """
153
+ **Note:** This example uses YOLOv8 for object detection. Lane detection is a more complex task and requires additional image processing techniques. This is a simplified demo and will likely not perform well on complex or noisy video.
154
+ """
155
+ )
Yolov8/requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ streamlit
2
+ opencv-python
3
+ pillow
4
+ numpy
5
+ ultralytics