|
import streamlit as st |
|
import cv2 |
|
import numpy as np |
|
from ultralytics import YOLO |
|
from tempfile import NamedTemporaryFile |
|
import os |
|
|
|
|
|
model = YOLO("yolov8n.pt") |
|
|
|
|
|
|
|
st.markdown("Created by: [Engr. Hamesh Raj](https://www.linkedin.com/in/datascientisthameshraj/)") |
|
|
|
st.title("🎥 YOLOv8 Object Detection on Videos") |
|
|
|
|
|
st.sidebar.header("Upload Video") |
|
uploaded_video = st.sidebar.file_uploader("Choose a video...", type=["mp4", "mov", "avi", "mkv"]) |
|
|
|
if uploaded_video is not None: |
|
|
|
temp_video = NamedTemporaryFile(delete=False) |
|
temp_video.write(uploaded_video.read()) |
|
video_path = temp_video.name |
|
|
|
|
|
st.sidebar.video(uploaded_video) |
|
|
|
|
|
if st.sidebar.button("Submit"): |
|
st.subheader("Processing Video...") |
|
|
|
|
|
cap = cv2.VideoCapture(video_path) |
|
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) |
|
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) |
|
fps = cap.get(cv2.CAP_PROP_FPS) |
|
|
|
|
|
temp_output_video = NamedTemporaryFile(delete=False, suffix='.mp4') |
|
output_video_path = temp_output_video.name |
|
|
|
|
|
fourcc = cv2.VideoWriter_fourcc(*'mp4v') |
|
out = cv2.VideoWriter(output_video_path, fourcc, fps, (frame_width, frame_height)) |
|
|
|
|
|
while cap.isOpened(): |
|
ret, frame = cap.read() |
|
if not ret: |
|
break |
|
|
|
|
|
results = model(frame) |
|
|
|
|
|
for result in results: |
|
for box in result.boxes: |
|
x1, y1, x2, y2 = map(int, box.xyxy[0]) |
|
conf = box.conf[0] |
|
cls = box.cls[0] |
|
label = f'{model.names[int(cls)]} {conf:.2f}' |
|
|
|
cv2.rectangle(frame, (x1, y1), (x2, y2), (255, 0, 0), 2) |
|
cv2.putText(frame, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 0, 0), 2) |
|
|
|
out.write(frame) |
|
|
|
cap.release() |
|
out.release() |
|
|
|
|
|
st.subheader("Processed Video") |
|
st.video(output_video_path) |
|
|
|
|
|
with open(output_video_path, "rb") as file: |
|
st.download_button( |
|
label="Download Processed Video", |
|
data=file, |
|
file_name="processed_video.mp4", |
|
mime="video/mp4" |
|
) |
|
|
|
|
|
os.remove(video_path) |
|
os.remove(output_video_path) |
|
|