wesam0099 commited on
Commit
886c9f4
·
verified ·
1 Parent(s): 42d050d

Create streamlitUI.py

Browse files
Files changed (1) hide show
  1. streamlitUI.py +155 -0
streamlitUI.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import tempfile
4
+ import requests
5
+ import base64
6
+ import numpy as np
7
+ from PIL import Image
8
+ from io import BytesIO
9
+ from ultralytics import YOLO
10
+ import streamlit as st
11
+ import yt_dlp as youtube_dl
12
+
13
+ def load_yolov8_model(model_name='yolov8s.pt'):
14
+ try:
15
+ return YOLO(model_name)
16
+ except Exception as e:
17
+ st.error(f"Error loading model: {e}")
18
+ return None
19
+
20
+ def detect_objects(image, model):
21
+ try:
22
+ results = model(image)
23
+ for result in results[0].boxes:
24
+ x1, y1, x2, y2 = map(int, result.xyxy[0])
25
+ label = model.names[int(result.cls)]
26
+ confidence = result.conf.item()
27
+ cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
28
+ label_text = f'{label} {confidence:.2f}'
29
+ cv2.putText(image, label_text, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
30
+ return image
31
+ except Exception as e:
32
+ st.error(f"Error during object detection: {e}")
33
+ return None
34
+
35
+ def process_image_with_yolov8(model_name, image=None, url=None):
36
+ model = load_yolov8_model(model_name)
37
+ if model is None:
38
+ return None
39
+
40
+ if url:
41
+ if url.startswith('data:image'):
42
+ try:
43
+ header, encoded = url.split(',', 1)
44
+ image_data = base64.b64decode(encoded)
45
+ image = Image.open(BytesIO(image_data))
46
+ except Exception as e:
47
+ st.error(f"Error decoding base64 image: {e}")
48
+ return None
49
+ else:
50
+ try:
51
+ response = requests.get(url)
52
+ response.raise_for_status()
53
+ image = Image.open(BytesIO(response.content))
54
+ except Exception as e:
55
+ st.error(f"Error loading image from URL: {e}")
56
+ return None
57
+
58
+ try:
59
+ image = np.array(image)
60
+ output_image = detect_objects(image, model)
61
+ return output_image
62
+ except Exception as e:
63
+ st.error(f"Error processing image: {e}")
64
+ return None
65
+
66
+ def download_youtube_video(youtube_url):
67
+ try:
68
+ temp_dir = tempfile.gettempdir()
69
+ output_path = os.path.join(temp_dir, 'downloaded_video.mp4')
70
+ ydl_opts = {
71
+ 'format': 'best',
72
+ 'outtmpl': output_path
73
+ }
74
+ with youtube_dl.YoutubeDL(ydl_opts) as ydl:
75
+ ydl.download([youtube_url])
76
+ return output_path
77
+ except Exception as e:
78
+ st.error(f"Failed to retrieve video from YouTube. Error: {e}")
79
+ return None
80
+
81
+ def process_video(input_video_path, output_video_path, model):
82
+ cap = cv2.VideoCapture(input_video_path)
83
+ if not cap.isOpened():
84
+ st.error(f"Error: Cannot open video file {input_video_path}")
85
+ return None
86
+
87
+ frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
88
+ frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
89
+ fps = cap.get(cv2.CAP_PROP_FPS)
90
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
91
+
92
+ out = cv2.VideoWriter(output_video_path, fourcc, fps, (frame_width, frame_height))
93
+
94
+ while True:
95
+ ret, frame = cap.read()
96
+ if not ret:
97
+ break
98
+
99
+ processed_frame = detect_objects(frame, model)
100
+ out.write(processed_frame)
101
+
102
+ cap.release()
103
+ out.release()
104
+
105
+ return output_video_path
106
+
107
+ st.title("YOLOv8 Object Detection on Images and Videos")
108
+
109
+ model_choice = st.selectbox("Select Model", ["yolov8s.pt", "yolov8m.pt"])
110
+
111
+ tabs = st.tabs(["Image Detection", "Video Detection"])
112
+
113
+ with tabs[0]:
114
+ st.header("Image Detection")
115
+ input_choice = st.radio("Select Input Method", ["Upload", "URL"])
116
+
117
+ if input_choice == "Upload":
118
+ uploaded_image = st.file_uploader("Upload Image", type=["jpg", "jpeg", "png"])
119
+ if uploaded_image is not None:
120
+ image = Image.open(uploaded_image)
121
+ processed_image = process_image_with_yolov8(model_choice, image=image)
122
+ if processed_image is not None:
123
+ st.image(processed_image, caption="Processed Image", use_column_width=True)
124
+ elif input_choice == "URL":
125
+ image_url = st.text_input("Image URL")
126
+ if image_url:
127
+ processed_image = process_image_with_yolov8(model_choice, url=image_url)
128
+ if processed_image is not None:
129
+ st.image(processed_image, caption="Processed Image", use_column_width=True)
130
+
131
+ with tabs[1]:
132
+ st.header("Video Detection")
133
+ video_choice = st.radio("Select Input Method", ["Upload", "YouTube"])
134
+
135
+ if video_choice == "Upload":
136
+ uploaded_video = st.file_uploader("Upload Local Video", type=["mp4", "mov", "avi"])
137
+ if uploaded_video is not None:
138
+ input_video_path = os.path.join(tempfile.gettempdir(), uploaded_video.name)
139
+ with open(input_video_path, "wb") as f:
140
+ f.write(uploaded_video.read())
141
+ model = load_yolov8_model(model_choice)
142
+ output_video_path = os.path.join(tempfile.gettempdir(), "processed_video.mp4")
143
+ processed_video = process_video(input_video_path, output_video_path, model)
144
+ if processed_video is not None:
145
+ st.video(processed_video)
146
+ elif video_choice == "YouTube":
147
+ video_url = st.text_input("YouTube Video URL")
148
+ if video_url:
149
+ input_video_path = download_youtube_video(video_url)
150
+ if input_video_path:
151
+ model = load_yolov8_model(model_choice)
152
+ output_video_path = os.path.join(tempfile.gettempdir(), "processed_video.mp4")
153
+ processed_video = process_video(input_video_path, output_video_path, model)
154
+ if processed_video is not None:
155
+ st.video(processed_video)